广播的发送与接收通过UDP套接字来实现的。广播包发送的流程如下:
(1)创建UDP套接字。
(2)指定目标地址和端口(填充广播信息结构体)。
(3)设置套接字选项允许发送广播包。
(4)发送广播消息。
发送广播包的示例代码如下所示。通过setsockopt()设置网络属性,允许进行广播。
1 #include <stdio.h>
2 #include <arpa/inet.h>
3 #include <sys/types.h>
4 #include <sys/socket.h>
5 #include <netinet/in.h>
6 #include <stdlib.h>
7 #include <unistd.h>
8 #include <string.h>
9
10 #define N 128
11 #define errlog(errmsg) do{perror(errmsg);\
12 printf("%s--%s--%d\n",\
13 __FILE__, __func__, __LINE__);\
14 exit(1);\
15 }while(0)
16
17 int main(int argc, const char *argv[])
18 {
19 int sockfd;
20 struct sockaddr_in broadcastaddr;
21 socklen_t addrlen = sizeof(broadcastaddr);
22 char buf[N] = {};
23
24 if(argc < 3)
25 {
26 fprin