我想从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);
}
答案 0 :(得分:2)
如果您使用的是TCP或连接的UDP,请使用Socket.LocalEndPoint
和Socket.RemoteEndPoint
属性。
如果您使用的是无连接UDP,则应使用Begin/EndReceiveFrom()
而不是Begin/EndReceive()
。回调为发件人提供EndPoint
。
无论哪种方式,给定EndPoint
对象,将其强制转换为IPEndPoint
并使用其Address
属性访问IP地址。