服务器端代码
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<unistd.h>
4 #include<string.h>
5 #include<sys/socket.h>
6 #include<sys/types.h>
7 #include<arpa/inet.h>
8 #include<sys/stat.h>
9 #include<net/if.h>
10 int main(int argc, char*trgv[])
11 { //创建套接字
12 int lfd=socket(AF_INET,SOCK_DGRAM,0);
13 //构建IP和端口
14 struct sockaddr_in serv;
15 memset(&serv,0,sizeof(serv));
16 serv.sin_family=AF_INET;
17 serv.sin_port=htons(8787);
serv.sin_addr.s_addr=htonl(INADDR_ANY);
19 //绑定套接字
20 int ret=bind(lfd,(const struct sockaddr *)&serv,sizeof(serv));
21 //客户端IP和端口
22 struct sockaddr_in cli;
23 cli.sin_family=AF_INET;
24 cli.sin_port=htons(6767);
25 inet_pton(AF_INET,"239.0.0.0",&cli.sin_addr.s_addr);
26 //设置组播
27 struct ip_mreqn flag;
28 inet_pton(AF_INET,"239.0.0.0",&flag.imr_multiaddr.s_addr);//组播地址
29 inet_pton(AF_INET,"0.0.0.0",&flag.imr_address.s_addr);//本地IP
30 flag.imr_ifindex=if_nametoindex("eth0");//网卡编号
31 setsockopt(lfd,IPPROTO_IP,IP_MULTICAST_IF,&flag,sizeof(flag));
32 //开始组播
33 int num=0;
34 while(1)
35 {
36
37 char buf[128]={0};
38 sprintf(buf,"hello,udp==%d\n",num++);
39 ret=sendto(lfd,buf,sizeof(buf),0,(const struct sockaddr*)&cli,sizeof(cli));
40 if(ret==-1)
41 {
42 perror("sendto is error\n");
43 }
44 printf("this is %s\n",buf);
45 sleep(1);
46 }
47 close(lfd);
48 return 0;
49
50 }
客户端代码
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<string.h>
4 #include<sys/stat.h>
5 #include<sys/types.h>
6 #include<unistd.h>
7 #include<arpa/inet.h>
8 //#include<sys/socket.h>
9 //#include<net/if.h>
10 int main(int argc,char*argv[])
11 {
12 //创建套接字
13 int fd =socket(AF_INET,SOCK_DGRAM,0);
14 //创建客户端IP和端口
15 struct sockaddr_in cli;
16 cli.sin_family=AF_INET;
17 cli.sin_port=htons(6767);
18 inet_pton(fd,"0.0.0.0",&cli.sin_addr.s_addr);
19 bind(fd,(struct sockaddr*)&cli,sizeof(cli));
20 //加入组播
21 struct ip_mreqn flag;
22 inet_pton(AF_INET,"239.0.0.0",&flag.imr_multiaddr.s_addr);
23 inet_pton(AF_INET,"0.0.0.0",&flag.imr_address.s_addr);
24 flag.imr_ifindex=if_nametoindex("eth0");
25 setsockopt(fd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&flag,sizeof(flag));
26 //通信
27 while(1)
28 {
29 char buf[128]={0};
30 int ret=recvfrom(fd,buf,sizeof(buf),0,NULL,NULL);
31 if(ret==-1)
32 {
33 perror("recv error\n");
34 exit(1);
35 }
36 printf("recv %s\n",buf);
37 }
38 close(fd);
39 return 0;
40 }