C#获取UDP服务器套接字从其接收数据的客户端的IP地址

C# Getting the IP Address of the client which the UDP server socket received data from

我有一个很奇怪的问题。我无法找到我的服务器从中接收数据的客户端的 IP 地址。下面是我的 UDP 侦听器 class.

IPPacketInformation 不包含 IP。我在 EndReceiveMessageFrom 中引用的 clientEndPoint 两者都没有。

当我

Console.Writeline(((IPEndPoint)clientEndPoint).Address); 

我得到了服务器的 IP 地址。我将服务器托管在我自己的机器上,所以我有自己的 IP 地址。当我尝试访问 clientEndPoint.remoteEndPoint 时,它会抛出错误,因为套接字未连接(由于是 UDP)。

所以基本上,来自外部 IP 的客户端能够发送数据,但我无法回复客户端,因为我无法检索它的 IP。感谢您的帮助!

public class UdpListener
{
    private Socket s;
    public byte[] ReceiveBuffer = new byte[2048];

    public UdpListener()
    {
        s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
        s.Bind(new IPEndPoint(IPAddress.Any, 36200));
    }

    public void Listen()
    {
        try
        {
            EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
            s.BeginReceiveMessageFrom(ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, Recv, s);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            throw;
        }
    }

    private void Recv(IAsyncResult res)
    {
        try
        {
            Socket receiveSocket = (Socket)res.AsyncState;

            EndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, 0);
            IPPacketInformation packetInfo;
            SocketFlags flags = SocketFlags.None;
            int udpMessageLength = receiveSocket.EndReceiveMessageFrom(res, ref flags, ref clientEndPoint, out packetInfo);
            byte[] udpMessage = new byte[udpMessageLength];
            Array.Copy(ReceiveBuffer, udpMessage, udpMessageLength);

            Console.WriteLine(
                "{0} bytes received from {1} to {2}",
                ReceiveBuffer,
                clientEndPoint,
                packetInfo.Address
            );

            EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, ((IPEndPoint)receiveSocket.LocalEndPoint).Port);
            s.BeginReceiveMessageFrom(ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, Recv, s);

            //Process data
            RaiseDataReceived(new ReceivedDataArgs(packetInfo.Address, ((IPEndPoint)clientEndPoint).Port, udpMessage));
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            throw;
        }
    }

    public delegate void DataReceived(ReceivedDataArgs args);

    public event DataReceived DataReceivedEvent;

    private void RaiseDataReceived(ReceivedDataArgs args)
    {
        DataReceivedEvent?.Invoke(args);
    }
}

我试过禁用我的防火墙,但没有用。我还在我的路由器上完成了端口转发,因此我可以从外部客户端接收数据。

编辑 澄清问题:

服务器托管在我机器上的 NAT 后面,public IP 214.214.214.214。

客户端是另一台机器,在另一个 NAT 后面,public IP 910.910.910.910。

客户端向服务端发送消息,服务端接收并读取内容。当服务器获取客户端的IPEndPoint时,显示的IP为214.214.214.214(服务器的IP,不是客户端

编辑 也许我应该说,在我从我的 ISP 订购 "Dynamic IP" 之前,我无法从外部网络上的客户端接收消息。仍然无法获取来源的 public IP。

编辑 当使用 Wireshark 并嗅探从外部客户端发送到我的服务器的数据包时,我可以看到它也是错误的 src IP。下图中的 src IP 是我的服务器 IP,而不是发送数据的客户端 IP。

使用 UdpClient class 您实际上可以在收到消息时检索远程端点。

我使用了如下解决方案来解决此任务:

public void StartServer()
{
    var udpServer = new UdpClient(new IPEndPoint(IPAddress.Any, ConnectionInformation.DETECTION_PORT));
    udpServer.BeginReceive(new AsyncCallback(detectionCallback), udpServer);
}

private void detectionCallback(IAsyncResult ar)
{
    var client = (ar.AsyncState as UdpClient);
    if (client.Client == null) return;

    var endPoint = new IPEndPoint(IPAddress.Any, ConnectionInformation.DETECTION_PORT);
    var bytes = client.EndReceive(ar, ref endPoint);

    Debug.WriteLine($"Detection request from: {endPoint}");
}

经过几天的阅读,我可能会阅读有关路由器、网络的所有内容并编写 Receive、ReceiveFrom、ReceiveMessageFrom、BeginReceive、BeginReceiveFrom、BeginReceiveMessageFrom 和 [=16= 的不同示例]ReceiveAsync - 我已经解决了我的问题。

我更换了我的路由器。我现在可以使用一个非常旧的路由器获取外部客户端的源IP。我之前使用的路由器是新的 Docsis 3.1。

为什么它与旧路由器一起工作,我不知道,但出于某种原因,Docsis 3.1 在让 UDP 消息到达我的机器之前将源 IP 更改为它自己的 IP。