UDP套接字从一个IP地址接收数据包,而忽略其他IP地址

时间:2018-07-09 01:31:29

标签: c# sockets networking udp

我遇到一个问题,我在一个端口49473上打开了UDP套接字,而一个IP地址却被识别,而另一个IP地址却没有。我在来自18.x.x.x和24.x.x.x的wireshark数据包中仅看到正在读取的18.x.x.x数据包。任何想法可能会发生什么? (未遍历18.x.x.x的旁注,但不确定24.x.x.x是否会有所不同..)另外,我尝试将缓冲区从8192增加到150k,这没有帮助。缓冲区没有丢弃数据包,因此不幸的是。

wireshark中的图像单击到enlarge

    public UdpSocket(int port = 0)
    {
        sw.Start();

        _buffer.Client = this;

        if (port != 0)
            _buffer.IsHost = true;

        _discovery = new Discovery(_buffer);
        _buffer.NatOp = new NatOperation(_buffer, _buffer.IsHost);

        _endPoint = new IPEndPoint(IPAddress.Any, port);
        _buffer.Stream = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        _buffer.Stream.ReceiveBufferSize = 8192;
        _buffer.Stream.SendBufferSize = 8192;
        _buffer.Stream.EnableBroadcast = true;

        //***********Magic Fairy Dust*************
        uint IOC_IN = 0x80000000;
        uint IOC_VENDOR = 0x18000000;
        uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
        _buffer.Stream.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
        //*********** Fairy Dust End *************

        _buffer.Stream.Bind(_endPoint);

        Thread receive = new Thread(ReceiveUdp);
        Thread send = new Thread(SendThread);

        receive.IsBackground = true;
        send.IsBackground = true;

        receive.Start();
        send.Start();
    }

    private void ReceiveUdp()
    {
        while (IsRunning)
        {
            try
            {
                Packet packet = _buffer.CreatePacket();
                EndPoint _ep = new IPEndPoint(IPAddress.Any, 0);
                count = _buffer.Stream.ReceiveFrom(data, 1024, SocketFlags.None, ref _ep);

                if (((IPEndPoint)_ep).Address.ToString() != "18.x.x.x")
                    Console.WriteLine("Foreign Address Connection " + packet.RemoteEp.Address.ToString()); //never returns so 18.x.x.x only processing 

                packet.Data.MirrorData(count, data);
                packet.RemoteEp = _ep as IPEndPoint;

                packet.ReadHeader();

                lock (_inProcess)
                    _inProcess.Enqueue(packet);
            }
            catch { }
        }
    }

对于阅读此SendTo和ReceiveFrom的任何人来说,ICD响应都会使魔术仙子禁用该响应,此解决方案仅适用于Windows / Linux。 我也接受了不受限制的SocketOptions IP正确性。在我的情况下,Socket.Connect是问题所在,当您执行此操作时,它仅允许该IP进行传输。

1 个答案:

答案 0 :(得分:1)

这可能是与NAT相关的问题。尝试

_buffer.Stream.SetIPProtectionLevel(IPProtectionLevel.Unrestricted);

Bind之前或之后。 UDPClient通过方法AllowNatTraversal做到了这一点。

或者这可能是与防火墙/ AV相关的问题。暂时关闭它们并尝试一下。