C/C++ Socket UDP 广播消息的发送与接收
局域网内全网段广播消息的IP地址为:255.255.255.255,向该IP地址发送广播消息,局域网下的任何网段的客户机都能收到广播。
对于发送端,如果你只想给某个特定的网段发送消息,例如你的IP地址为192.168.31.107,那么你的广播地址是192.168.31.255,向该广播地址发送广播消息,只有192.168.31.XXX网段下的客户机能收到广播。
同样,对于接收端,绑定了广播地址0.0.0.0这个IP即可。
C语言 UDP 广播简单示例(linux系统下):
/*
* main.c
*
* Created on: Sep 26, 2022
* Author: root
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#define BOARDCAST_IP "255.255.255.255"
#define BOARDCAST_PORT 10130
int broadcast_send(void)
{
int fd;
int ret;
int on;
struct sockaddr_in addr;
const char* message = "This is boardcast message !";
fd = socket(AF_INET, SOCK_DGRAM, 0);
if(fd < 0)
{
fprintf(stderr, " create socket failed ! \n");
goto __exit;
}
on = 1;
ret = setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on));
if(ret < 0)
{
fprintf(stderr, " setsockopt failed ! \n");
goto __exit;
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(BOARDCAST_PORT);
addr.sin_addr.s_addr = inet_addr(BOARDCAST_IP);
ret = sendto(fd, message, strlen(message), 0, (struct sockaddr *)&addr, sizeof(addr));
if(fd < 0)
{
fprintf(stderr, " boardcast failed ! \n");
goto __exit;
}
printf(" send ok ! \n");
__exit:
close(fd);
return 0;
}
int broadcast_recv(void)
{
int fd;
int ret;
int on;
struct sockaddr_in addr, addr_from;
char message[512];
socklen_t len;
fd = socket(AF_INET, SOCK_DGRAM, 0);
if(fd < 0)
{
fprintf(stderr, " create socket failed ! \n");
goto __exit;
}
on = 1;
ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
if(ret < 0)
{
fprintf(stderr, " setsockopt failed ! \n");
goto __exit;
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(BOARDCAST_PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
ret = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
if(ret < 0)
{
fprintf(stderr, " bind failed ! \n");
goto __exit;
}
memset(message, 0X00, sizeof(message));
len = sizeof(addr_from);
ret = recvfrom(fd, message, sizeof(message), 0, (struct sockaddr *)&addr_from, &len);
if(ret < 0)
{
fprintf(stderr, " recv failed ! \n");
goto __exit;
}
printf(" recv: [%s] ok ! \n", message);
__exit:
close(fd);
return 0;
}
int main(int argc, const char* argv[])
{
if(argc == 2)
{
if(strcmp(argv[1], "recv") == 0)
{
broadcast_recv();
}
if(strcmp(argv[1], "send") == 0)
{
broadcast_send();
}
}else
{
printf("\r\n");
printf("########################################### \r\n");
printf("Usage: %s [ recv | send ] \r\n", argv[0]);
printf("e.g. : %s recv\r\n", argv[0]);
printf("e.g. : %s send\r\n", argv[0]);
printf("########################################### \r\n");
}
return 0;
}
程序运行结果:
ends…