C#套接字网络定向广播

本文关键字:广播 网络 套接字 | 更新日期: 2023-09-27 18:25:19

我有几个局域网(10.0.0.x)连接到WAN(192.168.1.x)。每个局域网都通过一个允许网络定向广播的路由器。这是为了允许WAN上的设备发现LAN中的设备。

我可以在局域网(10.0.0.255)上发送广播,并在我的插座上接收。但当我移动到广域网时,我可以在wireshark中看到它,但不能在我的插座中看到。换句话说,我有一个地址为10.0.0.1的设备通过网关向192.168.1.255发送相同的消息,但我的套接字没有接收到它。当这种情况发生时,源地址是路由器的地址。这是我插座的代码:

                    udpSocket = new Socket(AddressFamily.InterNetwork,
                        SocketType.Dgram, ProtocolType.Udp);
                    //Assign the any IP of the machine and listen on port number 5000
                    IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 5000);
                    //Bind this address to the server
                    udpSocket.Bind(ipEndPoint);
                    IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 5000);
                    //The epSender identifies the incoming clients
                    EndPoint epSender = (EndPoint)ipeSender;
                    //Start receiving data
                    udpSocket.BeginReceiveFrom(byteData, 0, byteData.Length,
                        SocketFlags.None, ref epSender, new AsyncCallback(ReceiveAnnounce), epSender);

我对每条消息都有一个wireshark跟踪,但我不确定发布它的最佳方式。谢谢。

C#套接字网络定向广播

您知道UDP不能保证接收到数据包吗?(TCP使用客户端到服务器的连接),并且数据包被广播到"多播组"(这类似于IP地址,但必须在224.0.0.0239.255.255.255的范围内)而不是IP。

你对IPAddress.Any的使用告诉它使用所有网络接口,但你从来没有告诉它使用哪个多播组,我自己在C#中从来没有这样做过,但看起来你想在BeginReceiveFrom之前添加这行代码;

udpSocket.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.AddMembership,new MulticastOption(TARGET_IP)); 

您应该将TARGET_IP替换为您希望侦听的多播组的地址。

我从这个网站上取了那行代码;http://osix.net/modules/article/?id=409