C ++接收UDP广播数据包

时间:2018-08-06 12:57:48

标签: c++ linux sockets udp broadcast

我编写了一个UDP广播程序,用于在子网192.168.1.255,端口19000上广播数据包-假设它在机器A 192.168.1.26上运行。这基于http://beej.us/guide/bgnet/html/single/bgnet.html#broadcast。删除错误检查后,它看起来像:

struct hostent* he = gethostbyname("192.168.1.255");

int fd = socket(AF_INET, SOCK_DGRAM, 0);

int broadcast = 1;
int errors = setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(int));

struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr = *((struct in_addr*) he->h_addr);
memset(addr.sin_zero, '\n', sizeof(addr.sin_zero));

const char* message = "Hi there";
int len = strlen(message);
int bytes_sent = sendto(fd, data, len, 0, (struct sockaddr*) &addr, sizeof(addr));

我已经编写了一个相应的接收器应用程序,该应用程序将在与广播器相同的网络上的计算机上分发。这基于http://beej.us/guide/bgnet/html/single/bgnet.html#datagram。同样,删除错误检查后,该程序如下所示:

struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE;

struct addrinfo* servinfo;
int rv = getaddrinfo(NULL, "19000", &hints, &servinfo);

int fd = -1;
struct addrinfo* p;
for (p = servinfo; p != NULL; p = p->ai_next)
{
    fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);

    int errors = bind(fd, p->ai_addr, p->ai_addrlen);

    int broadcast = 1;
    errors |= setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(int));

    if (errors == 0)
         break;
}

freeaddrinfo(servinfo);

struct sockaddr their_addr;
socklen_t addr_len = sizeof(their_addr);

int bufsize = 4096;
char buf[bufsize];


int bytes_received = recvfrom(fd, &buf[0], bufsize, 0, (struct sockaddr*) &their_addr, &addr_len);

运行广播公司时,在Wireshark中,我可以看到以预期的源地址192.168.1.26和目标地址192.168.1.255传送到子网上的其他计算机的数据包。有效负载正确。但是,我的接收器应用程序未提取数据包。

如果我将广播公司更改为仅发送到单个接收方机器,例如192.168.1.58,该计算机上的接收器应用程序正确接收了数据包,但显然其他计算机没有。

我已禁用了两台计算机上的防火墙。

谁能建议出什么问题了?

0 个答案:

没有答案