UDP编程之二
广播模型
broadcast.c
1 #include <apue.h> 2 3 #define PORT 8088 4 5 int main(int argc,char **argv) 6 { 7 if(argc!=2) 8 { 9 printf("%s <msg>\n",argv[0]); 10 exit(0); 11 } 12 13 int sockfd; 14 if((sockfd = socket(AF_INET,SOCK_DGRAM,0))<0) 15 ERR("socket failed"); 16 17 //设置允许广播 18 int val = 1; 19 if(setsockopt(sockfd,SOL_SOCKET,SO_BROADCAST,&val,sizeof(val))<0) 20 ERR("setsockopt failed"); 21 22 struct sockaddr_in peer; 23 CLEAR(peer); 24 peer.sin_family = AF_INET; 25 peer.sin_port = htons(PORT); 26 inet_pton(AF_INET,"192.168.5.255",&peer.sin_addr); 27 28 if(sendto(sockfd,argv[1],strlen(argv[1]),0,(struct sockaddr*)&peer,sizeof(peer))<0) 29 ERR("send failed"); 30 31 close(sockfd); 32 return 0; 33 }
recv.c
#include <apue.h> #define PORT 8088 int main(int argc,char **argv) { int sockfd; if((sockfd = socket(AF_INET,SOCK_DGRAM,0))<0) ERR("socket failed"); struct sockaddr_in ipv4; CLEAR(ipv4); ipv4.sin_family = AF_INET; ipv4.sin_port = htons(PORT); ipv4.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(sockfd,(struct sockaddr*)&ipv4,sizeof(ipv4))<0) ERR("bind failed"); int n; char buf[255]; while(1) { if((n = recvfrom(sockfd,buf,sizeof(buf),0,NULL,NULL))<0) ERR("recv failed"); buf[n] = 0; printf("%s\n",buf); } close(sockfd); return 0; }