本文最后更新于 136 天前,其中的信息可能已经有所发展或是发生改变。
/**
* @filename: UDP_BROADCAST.c
* @brief: UDP_BROADCAST
* @author: philia
* @date: 2026/4/19
* @version: ver1.0
* @note NONE
* CopyRight (c) 2026 philia All Right Reseverd
*/
#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
int udp_socket;
int main(int argc, const char *argv[])
{
// 创建套接字文件
udp_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (udp_socket == -1)
{
fprintf(stderr, "udp_socket error, errno:%d,%s", errno, strerror(errno));
exit(-1);
}
int flag = -1;
int size = 4;
// 获取当前的广播属性
getsockopt(udp_socket, SOL_SOCKET, SO_BROADCAST,
(void *)&flag, &size);
printf("%d\n", flag);
int optval = 1;
// 设置广播属性
setsockopt(udp_socket, SOL_SOCKET, SO_BROADCAST,
&optval, 4);
// 再次获取当前的广播属性
getsockopt(udp_socket, SOL_SOCKET, SO_BROADCAST,
(void *)&flag, &size);
printf("%d\n", flag);
return 0;
}


