51 lines
1.8 KiB
C
51 lines
1.8 KiB
C
// 利用 setsocketopt() 使用嵌套字支持广播,并编写两个程序,其中一个发送广播数据,另一个接收广播数据
|
||
// 服务端
|
||
|
||
#include <stdio.h>
|
||
#include <stdlib.h>
|
||
#include <string.h>
|
||
#include <unistd.h>
|
||
#include <sys/types.h>
|
||
#include <sys/socket.h>
|
||
#include <netinet/in.h>
|
||
#include <arpa/inet.h>
|
||
|
||
int main(int argc, char const *argv[])
|
||
{
|
||
int sockfd = socket(AF_INET, SOCK_DGRAM, 0); // 创建UDP套接字
|
||
if (sockfd < 0)
|
||
{
|
||
perror("socket error");
|
||
exit(1);
|
||
}
|
||
|
||
char broadcast_msg[] = "this is a udp broadcast message"; // 广播消息
|
||
|
||
// 构造广播地址信息结构体对象
|
||
struct sockaddr_in broadcast_addr; // 广播地址信息结构体对象
|
||
memset(&broadcast_addr, 0, sizeof(broadcast_addr)); // 初始化广播地址信息结构体对象
|
||
broadcast_addr.sin_family = AF_INET; // 设置地址族
|
||
broadcast_addr.sin_port = htons(8000); // 设置端口号
|
||
broadcast_addr.sin_addr.s_addr = inet_addr("255.255.255.255"); // 设置广播地址
|
||
|
||
// 设置套接字选项,允许发送广播消息
|
||
int broadcast_enable_flag = 1;
|
||
// 说明:SOL_SOCKET表示当前套接字,SO_BROADCAST表示允许发送广播消息,&broadcast_enable_flag表示设置选项的值,sizeof(flag)表示选项值的大小
|
||
int ret = setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcast_enable_flag, sizeof(broadcast_enable_flag));
|
||
|
||
// 发送广播消息
|
||
ssize_t send_len = sendto(sockfd, broadcast_msg, strlen(broadcast_msg), 0, (struct sockaddr *)&broadcast_addr, sizeof(broadcast_addr));
|
||
if (send_len < 0)
|
||
{
|
||
perror("sendto error");
|
||
exit(1);
|
||
}
|
||
|
||
printf("广播消息发送成功 (%s)\n", broadcast_msg);
|
||
|
||
// 关闭套接字
|
||
close(sockfd);
|
||
|
||
return 0;
|
||
}
|