以下是一个使用C语言描述广播发送和接收的简单示例:

发送端(广播发送):

#include

#include

#include

#include

#include

#include

#include

#define BROADCAST_PORT 8888

#define BROADCAST_ADDRESS "192.168.1.255" // 替换为您的广播地址

int main() {

int sockfd;

struct sockaddr_in broadcastAddr;

char *broadcastMsg = "Hello, broadcast!";

// 创建UDP套接字

if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {

perror("socket creation failed");

exit(EXIT_FAILURE);

}

// 设置广播选项

int broadcastEnable = 1;

if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable)) < 0) {

perror("setsockopt failed");

exit(EXIT_FAILURE);

}

// 设置广播地址和端口

memset(&broadcastAddr, 0, sizeof(broadcastAddr));

broadcastAddr.sin_family = AF_INET;

broadcastAddr.sin_port = htons(BROADCAST_PORT);

if (inet_pton(AF_INET, BROADCAST_ADDRESS, &broadcastAddr.sin_addr) <= 0) {

perror("inet_pton failed");

exit(EXIT_FAILURE);

}

// 发送广播消息

if (sendto(sockfd, broadcastMsg, strlen(broadcastMsg), 0, (struct sockaddr*)&broadcastAddr, sizeof(broadcastAddr)) < 0) {

perror("sendto failed");

exit(EXIT_FAILURE);

}

printf("Broadcast message sent.\n");

close(sockfd);

return 0;

}

接收端(广播接收):

#include

#include

#include

#include

#include

#include

#include

#define BROADCAST_PORT 8888

int main() {

int sockfd;

struct sockaddr_in myAddr, senderAddr;

char recvBuffer[1024];

socklen_t senderLen = sizeof(senderAddr);

// 创建UDP套接字

if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {

perror("socket creation failed");

exit(EXIT_FAILURE);

}

// 设置接收端地址和端口

memset(&myAddr, 0, sizeof(myAddr));

myAddr.sin_family = AF_INET;

myAddr.sin_addr.s_addr = htonl(INADDR_ANY);

myAddr.sin_port = htons(BROADCAST_PORT);

// 绑定套接字到接收端地址

if (bind(sockfd, (struct sockaddr*)&myAddr, sizeof(myAddr)) < 0) {

perror("bind failed");

exit(EXIT_FAILURE);

}

// 接收广播消息

if (recvfrom(sockfd, recvBuffer, sizeof(recvBuffer)-1, 0, (struct sockaddr*)&senderAddr, &senderLen) < 0) {

perror("recvfrom failed");

exit(EXIT_FAILURE);

}

// 打印接收到的广播消息

printf("Received broadcast message: %s\n", recvBuffer);

close(sockfd);

return 0;

}

请注意,上述示例假设广播地址为192.168.1.255,并使用UDP套接字进行广播发送和接收。您可以根据实际情况进行适当的更改,包括广播地址和端口号。

在发送端,我们设置了套接字的广播选项,并将广播消息发送到指定的广播地址和端口。

在接收端,我们绑定套接字到指定的接收端地址和端口,并接收来自广播的消息。

注:广播发送和接收需要在同一个局域网中才能正常工作。

参考文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: