【问题标题】:How to detect destination IP address from UDP packets using UDPClient Class如何使用 UDPClient 类从 UDP 数据包中检测目标 IP 地址
【发布时间】:2014-04-16 22:54:46
【问题描述】:

我正在开发在客户端应用程序和服务器应用程序之间通过 UDP 发送和接收消息的应用程序。

在我的服务器上,我有 4 个不同的网卡,例如nic1 = 169.524.15.12, nic2 = 169.524.15.65 等。我的 DNS 指向 nic2。客户端应用程序解析 DNS 并将数据发送到 nic2。但是我的服务器应用程序有时会从 nic1 响应客户端。

我正在使用UdpClient 来监听传入的数据包。

这是我的服务器应用程序代码:

objSocketServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
EndPoint objEndPointOfServer =   new IPEndPoint(IPAddress.Any, 5000);
objSocketServer.Bind(objEndPointOfServer);
objSocketServer.BeginReceiveFrom(_arrReceivedDataBuffer, 0, BUFSIZE - 1, SocketFlags.None, ref objEndPointOfServer, DoReceiveFromClient, objSocketServer);

private void DoReceiveFromClient(IAsyncResult objIAsyncResult)
{
        try
        {
             // Get the received message.
            _objSocketReceivedClient = (Socket)objIAsyncResult.AsyncState;
            EndPoint objEndPointReceivedClient = new IPEndPoint(IPAddress.Any, 0);

            // Received data.
            int intMsgLen = _objSocketReceivedClient.EndReceiveFrom(objIAsyncResult, ref objEndPointReceivedClient);
            byte[] arrReceivedMsg = new byte[intMsgLen];
            Array.Copy(_arrReceivedDataBuffer, arrReceivedMsg, intMsgLen);

            // Client port.
            // Get and store port allocated to server1 while making request from client to server.
            int _intClientServer1Port = ((IPEndPoint)objEndPointReceivedClient).Port;

            // Send external ip and external port back to client.
            String strMessage = ((IPEndPoint)objEndPointReceivedClient).Address.ToString() + ":" + _intClientServer1Port.ToString();
            byte[] arrData = Encoding.ASCII.GetBytes(strMessage);
            objSocketServer.SendTo(arrData, arrData.Length, SocketFlags.None, objEndPointReceivedClient);

            // Start listening for a new message.
            EndPoint objEndPointNewReceivedClient = new IPEndPoint(IPAddress.Any, 0);
            objSocketServer.BeginReceiveFrom(_arrReceivedDataBuffer, 0, _arrReceivedDataBuffer.Length, SocketFlags.None, ref objEndPointNewReceivedClient, DoReceiveFromClient, objSocketServer)
        }
        catch (SocketException sx)
        {
                objSocketServer.Shutdown(SocketShutdown.Both);
                objSocketServer.Close();
        }
     }
}

有什么方法可以让我在代码中检测到我收到了服务器上哪个 IP 地址的数据包并返回具有相同 IP 的响应?

可以说,我也可以在服务器应用程序中解析 DNS,并确保我的服务器应用程序只侦听客户端应用程序发送数据包的 IP,但是当我的服务器应用程序必须侦听时,这种方法对我不起作用 > 1 个 IP。

【问题讨论】:

    标签: c# udp udpclient


    【解决方案1】:

    SendTo 命令将为所提供的目标地址使用适当的 NIC(也称为本地接口)。系统指标决定了这一点。这不是您在代码中设置的内容。要查看系统指标,请运行命令netstat -rn 并查看接口列。如果你有领带,你很多人需要调整这些。您也可以使用GetAllNetworkInterfaces() 在代码中枚举它们并绑定到特定的(如果这是您想要的)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      相关资源
      最近更新 更多