»
(008) CubeIDE Implementation of USB Peripherals*
(010) Linux UDP
(018) C99 pointer*
(019) C99 With only value assignment*
(022) POSIX pthread multi-threads mutex*
(023) POSIX pthread multi-threads programming*
(027) C99 time and wait*
(028) High-precision calculation with GMP*
(029) Web Service Lib*
(030) International Components for Unicode (ICU)*
(031) Performance of C is higher than C++, because...*
来自ChatGPT的UDP广播的总结:
1、创建 UDP 套接字
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);报错则 sockfd < 0
2、开启套接字为广播模式
setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &trueVal, sizeof(trueVal))); 如果报错则:返回值 < 0
3、绑定发送广播用的本机IP和本机端口号(UDP不需要握手,如果只发送,此步可以省略)
memset(&client_addr, 0, sizeof(client_addr));
client_addr.sin_family = AF_INET;
client_addr.sin_addr.s_addr = INADDR_ANY;//收发程序只监听端口,不固定IP
client_addr.sin_port = htons(PORT);
bind(sock_fd, (const struct sockaddr*)&client_addr, sizeof(client_addr))报错则:返回值 < 0
4、发向目标广播地址
struct sockaddr_in dest_addr;
memset(&dest_addr, 0, sizeof(dest_addr));
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(12345); // 设置目标端口
dest_addr.sin_addr.s_addr = inet_addr("192.168.1.255"); // 设置广播地址
sendto(sock_fd, ctnt, strlen(ctnt), 0, (const struct sockaddr*)&dest_addr, sizeof(dest_addr));
需要注意的是:发送端必须开启 SO_BROADCAST 广播模式。