UDP 客户端不发送

UDP Client Not Sending

我正在为一些我经常使用的设备开发一个自动发现客户端,我遇到了一个问题,对于某些用户来说,UDP 数据包没有被发送出去(它没有出现在 Wireshark 中)。

它背后的代码相当简单,我认为它与 Windows 防火墙有某种关系,但到目前为止我找不到解决方案。

任何人都可以就后续步骤提出任何建议吗?

相关代码:

class AutoDiscovery : IDisposable
{
    private UdpClient Udp;
    private static IPEndPoint BroadcastEP = new IPEndPoint(IPAddress.Broadcast, 12345);
    private List<byte> AutoDiscoverPacket = new List<byte>();

    private bool _IsDisposed = false;
    public bool IsDisposed
    {
        get { return _IsDisposed; }
        private set { _IsDisposed = value; }
    }

    public AutoDiscovery()
    {
        Udp = new UdpClient();
        Udp.ExclusiveAddressUse = false;
        Udp.EnableBroadcast = true;
        Udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        Udp.Client.Bind(new IPEndPoint(IPAddress.Any, 12345));
        ReceiveDataAsync(ReceiveDataCallback);

        AutoDiscoverPacket.AddRange(new byte[] { 0x14, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x03, 0x00, 0x00 });
        AutoDiscoverPacket.AddRange(Encoding.ASCII.GetBytes("SomeStaticString"));
        while (AutoDiscoverPacket.Count < 123)
        {
            AutoDiscoverPacket.Add(0x00);
        }
    }


    public void Discover()
    {
        if (IsDisposed) { throw new ObjectDisposedException("AutoDiscovery"); }
        Udp.Send(AutoDiscoverPacket.ToArray(), AutoDiscoverPacket.Count, BroadcastEP);
    }
}

确实显示使用

Udp.Client.Bind(new IPEndPoint(IPAddress.Any, 12345));

允许Windows自行决定绑定哪个适配器。我能够使用以下代码获取适配器 IP 地址列表,并创建一个绑定到每个地址的 UdpClient。

private List<IPAddress> GetEndpoints()
    {
        List<IPAddress> AddressList = new List<IPAddress>();
        NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
        foreach(NetworkInterface I in Interfaces)
        {
            if ((I.NetworkInterfaceType == NetworkInterfaceType.Ethernet || I.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) && I.OperationalStatus == OperationalStatus.Up)
            {
                foreach (var Unicast in I.GetIPProperties().UnicastAddresses)
                {
                    if (Unicast.Address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        AddressList.Add(Unicast.Address);
                    }
                }
            }
        }
        return AddressList;
    }