UDP 广播和接收单后无响应

问题描述

目前正在尝试通过 udp 访问我网络上的设备。 sendAsync 工作正常,但是在接收时我只收到一条消息。返回的消息

message received

是我相信发送的消息的响应,但所有正确响应的设备,在wireshark中查看都永远不会进入应用程序。不确定我是否缺少某些防火墙设置,或者接收器不在正确的 NIC 上,但已尝试各种选项并直接绑定到我计算机的 IP 地址。

    static async Task Main(string[] args)
        {
            await Task.Factory.StartNew(() => StartListener());
            // Give thread time to start listening
            Thread.Sleep(1000);

            var endpoint = new IPEndPoint(IPAddress.broadcast,56700);
            var sender = new UdpClient();
            sender.Client.Bind(new IPEndPoint(new UdpConnector(NetworkInterfaceType.Wireless80211,AddressFamily.InterNetwork).GetActiveIPAddresses(null).FirstOrDefault(),56700)); //Make sure were on the correct NIC
            sender.Client.Blocking = false;
            sender.DontFragment = true;
            sender.Client.Enablebroadcast = true;
            sender.Client.SetSocketoption(SocketoptionLevel.socket,SocketoptionName.ReuseAddress,true);
            sender.Connect(endpoint);
            var msg = new byte[] { 0x24,0x00,0x34,0x7B,0x01,0x02,0x00 };
            await sender.SendAsync(msg,msg.Length);

            Console.WriteLine("Message sent to the broadcast address");
            Console.ReadKey();
        }

        private const int Port = 56700;

        private static async Task StartListener()
        {
            UdpClient udpClient = new UdpClient();
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any,0);
            //udpClient.Client.Bind(groupEP);

            try
            {
                while (true)
                {
                    Console.WriteLine("Waiting for broadcast");
                    var bytes = await udpClient.ReceiveAsync();

                    Console.WriteLine("Received broadcast from {0} :\n {1}\n",bytes.RemoteEndPoint.ToString(),Encoding.ASCII.GetString(bytes.Buffer,bytes.Buffer.Length));
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                udpClient.Close();
            }
        }
    }

Wireshark trace

解决方法

对 Bind 的调用被注释掉了。

,

这是指向 Microsoft 文档的有关此主题的链接。可能对你有帮助: UdpClient.BeginReceive(AsyncCallback,Object) Method