获取接收到的数据的本地地址,UdpClient侦听任何ip地址



我有一个UdpClient正在侦听IPAddress.Any。当我接收数据时(当前使用ReceiveAsync,但如果需要,我可以更改它(,返回的UdpReceiveResult有一个带有远程端点(消息从哪里发送(的字段,但没有本地端点。既然我在听所有的ip地址,我怎么能知道它是在哪个ip地址上收到的?

我不知道*Async方法是否提供了相同的功能,但这里有一个实现,它为您提供了接收IP地址和接收UDP数据包的网络接口号。

通过使用底层的Sockets(Begin/End(ReceiveMessageFrom方法,我们可以获得有关已接收数据包的更多信息。其两个重要参数的代码文档是:

//   endPoint:
//     The source System.Net.EndPoint.
//
//   ipPacketInformation:
//     The System.Net.IPAddress and interface of the received packet.

我希望这能有所帮助。

static UdpClient client;
static byte[] byts = new byte[8192];
static void ReceiveUDP(IAsyncResult asyncResult)
{
EndPoint ipEndpoint = new IPEndPoint(IPAddress.Any, 9876);
IPPacketInformation packetInformation;
SocketFlags socketFlags = SocketFlags.None;
int numberOfBytesReceived = client.Client.EndReceiveMessageFrom(asyncResult, ref socketFlags, ref ipEndpoint, out packetInformation);
Console.WriteLine
(
"Received {0} bytesrnfrom {1}rnReceiving IP Address: {2}rnNetwork Interface #{3}rn************************************",
numberOfBytesReceived,
ipEndpoint,
packetInformation.Address,
packetInformation.Interface
);
EndPoint anyEndpoint = new IPEndPoint(IPAddress.Any, 9876);
try
{
client.Client.BeginReceiveMessageFrom(byts, 0, 8192, SocketFlags.None, ref anyEndpoint, ReceiveUDP, null);
}
catch (Exception beginReceiveError)
{
// Console.WriteLine("{0}", beginReceiveError);
}
}
static void Main(string[] args)
{
client = new UdpClient(new IPEndPoint(IPAddress.Any, 9876));
EndPoint anyEndpoint = new IPEndPoint(IPAddress.Any, 9876);
client.Client.BeginReceiveMessageFrom(byts, 0, 8192, SocketFlags.None, ref anyEndpoint, ReceiveUDP, null);
UdpClient server = new UdpClient();
server.Connect("172.20.10.4", 9876);
server.Send(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 8);
UdpClient server2 = new UdpClient();
server2.Connect("127.0.0.1", 9876);
server2.Send(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 9);
UdpClient server3 = new UdpClient();
server3.Connect("OOZGUL-NB02", 9876);
server3.Send(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 9);
client.Close();
server.Close();
server2.Close();
Console.ReadLine();
}

输出:

Received 8 bytes
from 172.20.10.4:59196
Receiving IP Address: 172.20.10.4
Network Interface #3
************************************
Received 9 bytes
from 127.0.0.1:59197
Receiving IP Address: 127.0.0.1
Network Interface #1
************************************
Received 9 bytes
from 172.20.10.4:59198
Receiving IP Address: 172.20.10.4
Network Interface #3
************************************

最新更新