我正在研究在客户端应用程序和服务器应用程序之间在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时,这种方法对我不起作用 .
1 回答
SendTo命令将使用适当的NIC(也称为本地接口)作为提供的目标地址 . 系统指标确定了这一点 . 这不是您在代码中设置的内容 . 要查看系统指标,请运行命令
netstat -rn
并查看“接口”列 . 如果你有平局,你很多人需要调整它们 . 您也可以使用GetAllNetworkInterfaces()
在代码中枚举它们并绑定到特定的(如果这是您想要的) .