从IAsyncResult UDP中提取IP

时间:2013-07-02 06:41:31

标签: sockets udp asyncsocket

我想从IAsyncResult UDP的对象中提取IP地址 EndReceive方法(IAsyncResult ar)

如果有可能,我该怎么做?

这里是代码:

public void End_Receive(IAsyncResult ir)
{
        //Here I need the sender IP
        ServerSocket.EndReceive(ir);
        ReceivedMessage =  System.Text.UnicodeEncoding.Unicode.GetString(buffer);
}

1 个答案:

答案 0 :(得分:2)

如果您使用的是TCP或连接的UDP,请使用Socket.LocalEndPointSocket.RemoteEndPoint属性。

如果您使用的是无连接UDP,则应使用Begin/EndReceiveFrom()而不是Begin/EndReceive()。回调为发件人提供EndPoint

无论哪种方式,给定EndPoint对象,将其强制转换为IPEndPoint并使用其Address属性访问IP地址。