【发布时间】: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。
【问题讨论】: