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

时间:2015-01-30 10:58:24

标签: .net sockets asynchronous network-programming udp

在将Socket类与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?
}

1 个答案:

答案 0 :(得分:1)

您需要使用BeginReceiveFrom和EndReceiveFrom,因为这些允许您传入对EndPoint的引用,如下所示:

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

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