linux 广播 UDP

UDP通信:广播

  向子网中多台计算机发送消息,并且子网中所有的计算机都可以接收到发送方发送的消息,每个广播消息都包含一个特殊的 IP 地址,这个 IP中子网内主机标志部分的二进制全部为 1(255)

    a. 只能在局域网中使用

    b. 客户端需要绑定服务器广播使用的端口,才可以接收到广播的消息

//设置广播属性的函数
int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen);
    - sockfd : 文件描述符
    - level : SOL_SOCKET
    - optname : SO_BROADCAST
    - optval : int类型的值 为1 允许广播
    - optlen : optval的大小

UDP广播客户端:

 1 #include <stdio.h>
 2 #include <arpa/inet.h>
 3 #include <stdlib.h>
 4 #include <unistd.h>
 5 #include <string.h>
 6 
 7 int main() 
 8 {
 9     //创建socket
10     int fd = socket(PF_INET, SOCK_DGRAM, 0);
11     if(fd == -1) 
12     {
13         perror("socket");
14         return -1;
15     }
16     //客户端绑定本地的IP和端口
17     struct sockaddr_in addr;
18     addr.sin_family = AF_INET;
19     addr.sin_port = htons(9999);
20     addr.sin_addr.s_addr = INADDR_ANY;
21     int ret = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
22     if(ret == -1)
23     {
24         perror("bind");
25         exit(-1);
26     }
27     //通信
28     while(1) 
29     {
30         char buf[128];
31         // 接收数据
32         int num = recvfrom(fd, buf, sizeof(buf), 0, NULL, NULL);
33         printf("server say: %s\n",buf);
34     }
35     close(fd);
36     return 0;
37 }

UDP广播服务端:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <unistd.h>
 4 #include <string.h>
 5 #include <arpa/inet.h>// #include <sys/types.h>  #include <sys/socket.h>
 6 
 7 int main()
 8 {
 9     //1.创建一个通信socket
10     int fd = socket(PF_INET, SOCK_DGRAM, 0);
11     if(fd == -1)
12     {
13         perror("socket");
14         exit(-1);
15     }
16     //2.设置广播属性
17     int op = 1;//1表示允许广播
18     setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &op, sizeof(op));
19     //3.创建一个广播的地址
20     struct sockaddr_in cliaddr;
21     cliaddr.sin_family = AF_INET;
22     cliaddr.sin_port = htons(9999);
23     inet_pton(AF_INET, "10.0.11.255", &cliaddr.sin_addr.s_addr);//广播ip
24     //3.通信
25     int num = 0;
26     while(1)
27     {
28        char sendBuf[128];
29        sprintf(sendBuf, "hello,client...%d\n",num++);
30        //发送数据
31        sendto(fd, sendBuf, strlen(sendBuf) + 1, 0, (struct sockaddr *)&cliaddr, sizeof(cliaddr));
32        printf("广播的数据 : %s\n",sendBuf);
33        sleep(1);
34     }
35     close(fd);
36     return 0;
37 }

 

posted on 2023-11-03 10:59  廿陆  阅读(110)  评论(0)    收藏  举报

导航