获取远程客户端发送到套接字的IP

Get IP of remote client sending to socket

在使用 .NET Socket class 和 BeginReceiveEndReceive 时,如何获取发送远程客户端的 IP?我只能检索发送的数据,但不能检索发送客户端的 IP 地址。

为简洁起见,伪代码示例已缩短且没有错误处理:

this.Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
this.Socket.Bind(localAddress);

this.Socket.BeginReceive(
    buffer,
    0,
    buffer.Length,
    SocketFlags.None,
    this.OnSocketDataReceived,
    null
);

protected override void OnSocketDataReceived(IAsyncResult asyn)
{
    SocketError socketError
    this.Socket.EndReceive(asyn, out socketError);
    // buffer contains data
    // how do I get the IP of the sending client?
}

您需要使用 BeginReceiveFrom 和 EndReceiveFrom,因为它们允许您传递对 EndPoint 的引用,如下所示:

IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint senderRemote = (EndPoint)sender;
this.Socket.EndReceiveFrom(asyn, ref senderRemote);

然后您可以从端点获取发送客户端的 IP 地址。