linux UDP廣播通訊
在除錯區域網內通過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.