1 #include <stdio.h>
2 #include <stdio.h>
3 #include <sys/socket.h>
4 #include <netinet/in.h>
5 #include <arpa/inet.h>
6 #include <sys/types.h>
7 #include <string.h>
8 #include <unistd.h>
9 #include <stdlib.h>
0 #include <sys/types.h>
1 #include <sys/stat.h>
2 #include <fcntl.h>
3 #include <pthread.h>
4
5 int sock_fd = -1;
6
7
8 void* sb_send(void* arg)
9 {
0 struct sockaddr_in zubo = *(struct sockaddr_in*)arg;
1
2
3 zubo.sin_family = AF_INET;
4 zubo.sin_port = htons(8844);
5 zubo.sin_addr.s_addr = inet_addr("224.10.10.10");
6
7 socklen_t zubo_len = sizeof(zubo);
8
9 bind(sock_fd,(struct sockaddr *)&zubo,zubo_len);
0
1
2
3 int a = 8848;
4 char b[]="192.168.124.123";
5 char join[100]="";
6 snprintf(join,100,"[prot:%d ip:%s<<< 我来了>>>] ",a,b);
7
8 sendto(sock_fd,join,100,0,(struct sockaddr *)&zubo,zubo_len);
9 char *buf = malloc(100);
0 while(1)
1 {
2 memset(buf,0,100);
3 fgets(buf,100,stdin);
4 sendto(sock_fd,buf,100,0,(struct sockaddr *)&zubo,zubo_len);
5
6 }
7
8 }
9 int main(int argc,char **argv)
0 {
1
2 //1.创建套接字
3 sock_fd = socket(AF_INET,SOCK_DGRAM,0);
4
5 //
6
7 //2.设置套接字的属性
8 //定义组播地址结构体,给组播地址成员赋值,给本机地址成员赋值
9 struct ip_mreq zubo;
0 zubo.imr_multiaddr.s_addr = inet_addr("224.10.10.10");
1 zubo.imr_interface.s_addr = INADDR_ANY;
2
3 socklen_t zubo_len = sizeof(zubo);
4 setsockopt(sock_fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &zubo, zubo_len);
5
6
7
8 //3.绑定
9 struct sockaddr_in local,opposite;
0 local.sin_family = AF_INET;
1 local.sin_port = htons(atoi(argv[1]));//10000
2 local.sin_addr.s_addr = INADDR_ANY;
3
4 socklen_t local_len = sizeof(local);
5 socklen_t opposite_len = sizeof(opposite);
6
7 bind(sock_fd,(struct sockaddr *)&local,local_len);
8
9 //广播
0 int bt = 1;
1 socklen_t len = sizeof(bt);
2 int ret = setsockopt(sock_fd, SOL_SOCKET, SO_BROADCAST, &bt, len);
3
4
5
6
7 pthread_t tid;
8
9 pthread_create(&tid,NULL, sb_send,(void*)&zubo);
0
1
2 // sendto(sock_fd,join,join_len,0,(struct sockaddr *)&opposite,opposite_len);
3 char *buf = malloc(100);
4 while(1)
5 {
6 memset(buf,0,100);
7 recvfrom(sock_fd,buf,100,0,(struct sockaddr *)&opposite,&opposite_len);
8
9
0 printf("from gropu:%s\n",buf);
1
2 }
3
Multicast 小组群聊
于 2024-08-21 22:36:11 首次发布