使用 UdpClient 监听任何 ip 地址获取接收数据的本地地址

get local address for recieved data with UdpClient listening on any ip address

我有一个 UdpClient 正在收听 IPAddress.Any。当我接收数据时(当前使用 ReceiveAsync,但如果需要我可以更改它),返回的 UdpReceiveResult 有一个包含远程端点(消息发送的地方)但不是本地端点的字段.我怎么知道它是在哪个 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} bytes\r\nfrom {1}\r\nReceiving IP Address: {2}\r\nNetwork Interface #{3}\r\n************************************",
        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
************************************