java判断udp包来自哪个网卡_如何使用UDPClient类从UDP数据包中检测目标IP地址

我正在研究在客户端应用程序和服务器应用程序之间在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时,这种方法对我不起作用 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值