UDP编程之三
三、组播模型
muticast.c
1 #include <apue.h> 2 3 #define PORT 8088 4 5 #define MULTIIP "225.0.0.1" 6 7 int main(int argc,char **argv) 8 { 9 if(argc!=2) 10 { 11 printf("%s <msg>\n",argv[0]); 12 exit(0); 13 } 14 15 int sockfd; 16 if((sockfd = socket(AF_INET,SOCK_DGRAM,0))<0) 17 ERR("socket failed"); 18 19 struct sockaddr_in peer; 20 CLEAR(peer); 21 peer.sin_family = AF_INET; 22 peer.sin_port = htons(PORT); 23 inet_pton(AF_INET,MULTIIP,&peer.sin_addr); 24 25 if(sendto(sockfd,argv[1],strlen(argv[1]),0,(struct sockaddr*)&peer,sizeof(peer))<0) 26 ERR("send failed"); 27 28 close(sockfd); 29 return 0; 30 }
recv.c
1 #include <apue.h> 2 3 #define PORT 8088 4 #define MULTIIP "225.0.0.1" 5 6 int main(int argc,char **argv) 7 { 8 int sockfd; 9 if((sockfd = socket(AF_INET,SOCK_DGRAM,0))<0) 10 ERR("socket failed"); 11 12 struct sockaddr_in ipv4; 13 CLEAR(ipv4); 14 ipv4.sin_family = AF_INET; 15 ipv4.sin_port = htons(PORT); 16 ipv4.sin_addr.s_addr = htonl(INADDR_ANY); 17 if(bind(sockfd,(struct sockaddr*)&ipv4,sizeof(ipv4))<0) 18 ERR("bind failed"); 19 20 //加入组 21 #if 0 22 struct ip_mreq{ 23 struct in_addr imr_multiaddr; /* IP multicast address of group */ 24 struct in_addr imr_interface; /* local IP address of interface */; 25 } 26 #endif 27 struct ip_mreq mreq; 28 inet_pton(AF_INET,MULTIIP,&mreq.imr_multiaddr); 29 mreq.imr_interface.s_addr = INADDR_ANY; 30 if(setsockopt(sockfd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&mreq,sizeof(mreq))<0) 31 ERR("setsockopt failed"); 32 33 int n; 34 char buf[255]; 35 while(1) 36 { 37 if((n = recvfrom(sockfd,buf,sizeof(buf),0,NULL,NULL))<0) 38 ERR("recv failed"); 39 buf[n] = 0; 40 printf("%s\n",buf); 41 } 42 43 //离开组 44 if(setsockopt(sockfd,IPPROTO_IP,IP_DROP_MEMBERSHIP,&mreq,sizeof(mreq))<0) 45 ERR("setsockopt failed"); 46 47 close(sockfd); 48 return 0; 49 }