如何使用UDPClient类从UDP数据包中检测目标IP地址

时间:2014-04-16 14:23:59

标签: c# udp udpclient

我正在研究在客户端应用和服务器应用之间在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,但是当我的服务器应用程序必须侦听&gt时,该方法对我不起作用; 1 IP。

1 个答案:

答案 0 :(得分:0)

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