接收 UDP 广播

2022-01-22 00:00:00 udp c++

我必须接收 UDP 广播(在 Ubuntu 中,如果这有什么不同的话).使用 Wireshark,我可以看到从服务器机器发送的数据包,并且我可以看到它正在被我的客户端机器接收,但我的程序完全没有注意到.这就是我所拥有的:

I have to receive an UDP broadcast (in Ubuntu if that makes any difference). Using Wireshark, I can see the packet being sent from the server machine, and I can see it being received by my client machine, but my program is completely oblivious. This is what I have:

sockaddr_in si_me, si_other;
int s;
assert((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))!=-1);
int port=6000;
int broadcast=1;

setsockopt(s, SOL_SOCKET, SO_BROADCAST,
            &broadcast, sizeof broadcast);

memset(&si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(port);
si_me.sin_addr.s_addr = INADDR_ANY;

assert(::bind(s, (sockaddr *)&si_me, sizeof(sockaddr))!=-1);

while(1)
{
    char buf[10000];
    unsigned slen=sizeof(sockaddr);
    recvfrom(s, buf, sizeof(buf)-1, 0, (sockaddr *)&si_other, &slen);

    printf("recv: %s
", buf);
}

它是在调试模式下编译的,编译过程中不会删除断言,我的程序只是阻塞在 recvfrom 上.

It is compiled in debug mode, the asserts aren't being erased during compilation, and my program just blocks on recvfrom.

为了接收非目标 UDP 广播,我是否必须跳过其他任何环节?

Is there any other hoop I have to jump through to receive an untargeted UDP broadcast?

再多一点信息,我将两台计算机连接在一个专用交换机上,没有外界干扰.我的客户端计算机上还有第二个网卡,它连接到公司网络,它也可以工作.

just a bit more info, I have the two computers connected on a dedicated switch, no outside interference. I also have a second network card on my client computer that connects to the company network, which also works.

我可以 ping 外部(互联网工作)和我的服务器机器(而且我可以在 Wireshark 中看到实际的数据包),但你永远不知道是什么导致了这个问题.

I can ping both the outside (Internet working) and my server machine (plus I can see the actual packets in Wireshark), but you never know what might cause this problem.

推荐答案

事实证明我的代码非常好,正如我所想的那样.网络设置本身存在问题.

As it turns out my code is perfectly fine, as I thought it would be. There was a problem with the network setup itself.

为了后代,我在它们自己的集线器上设置了两台静态 IP 计算机,而不是使用服务器机器上的内置 DHCP 服务器为另一台计算机分配 IP 地址.我的问题非常本地化,但你永远不知道..

For posterity, I had set up two static IP'd computers on their own hub, instead of using the built in DHCP server on the server machine to allocate the IP address for the other computer. Pretty localized for my problem but you never know..

相关文章