在调试局域网内通过UDP协议获取其他设备IP地址时,服务器使用UDP 广播后, 客户端设备无响应. 先研究一下正常情况下, UDP广播通信方法. 参考了网络上一写资料. 代码整理如下:
服务器端向: 255.255.255.255:6023发送UDP广播:
serverUDP.c
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#define PORT 6023
int main()
{
setvbuf(stdout, NULL, _IONBF, 0);
fflush(stdout);
int sock = -1;
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
printf("socket error\n");
return -1;
}
const int opt = 1;
//设置该套接字为广播类型,
int nb = 0;
nb = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));
if(nb == -1)
{
printf("set socket error...\n");
return -1;
}
struct sockaddr_in addrto;
bzero(&addrto, sizeof(struct sockaddr_in));
addrto.sin_family=AF_INET;
addrto.sin_addr.s_addr=htonl(INADDR_BROADCAST);
addrto.sin_port=htons(PORT);
int nlen=sizeof(addrto);
while(1)
{
sleep(1);
//从广播地址发送消息
char smsg[] = {"abcdef"};
int ret=sendto(sock, smsg, strlen(smsg), 0, (struct sockaddr*)&addrto, nlen);
if(ret<0)
{
printf("send error....\n");
}
else
{
printf("ok \n");
}
}
return 0;
}
客户端接收广播消息.
clientUDP.c
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define PORT 6023
int main()
{
setvbuf(stdout, NULL, _IONBF, 0);
fflush(stdout);
// 绑定地址
struct sockaddr_in addrto;
bzero(&addrto, sizeof(struct sockaddr_in));
addrto.sin_family = AF_INET;
addrto.sin_addr.s_addr = htonl(INADDR_ANY);
addrto.sin_port = htons(PORT);
// 广播地址
struct sockaddr_in from;
bzero(&from, sizeof(struct sockaddr_in));
from.sin_family = AF_INET;
from.sin_addr.s_addr = htonl(INADDR_ANY);
from.sin_port = htons(PORT);
int sock = -1;
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
printf("socket error\n");
return -1;
}
const int opt = 1;
//设置该套接字为广播类型,
int nb = 0;
nb = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));
if(nb == -1)
{
printf("set socket error...\n");
return -1;
}
if(bind(sock,(struct sockaddr *)&(addrto), sizeof(struct sockaddr_in)) == -1)
{
printf("bind error...\n");
return -1;
}
int len = sizeof(struct sockaddr_in);
char smsg[100] = {0};
while(1)
{
//从广播地址接受消息
int ret=recvfrom(sock, smsg, 100, 0, (struct sockaddr*)&from,(socklen_t*)&len);
if(ret<=0)
{
printf("read error....\n");
}
else
{
printf("%s\t", smsg);
}
sleep(1);
}
return 0;
}
Makefile:
all: server client
server:
gcc serverUDP.c -o serverUDP
client:
gcc clientUDP.c -o clientUDP
clean:
rm serverUDP clientUDP
如局域网内有A设备, IP为192.168.1.100, B设备, IP为192.168.1.101.
在A设备上运行 ./clientUDP &
在B设备上运行 ./serverUDP &
运行结果:
A设备上一直打印: abcdef
B设备上一直打印: ok.