Question

I want to extract IP address from an object of IAsyncResult UDP in EndReceive Method (IAsyncResult ar)

If it's possible, How can I do that?

Here the code:

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

Solution

If you are using TCP, or connected UDP, use the Socket.LocalEndPoint and Socket.RemoteEndPoint properties.

If you are using connection-less UDP, you should be using Begin/EndReceiveFrom() instead of Begin/EndReceive(). The callback provides an EndPoint for the sender.

Either way, given an EndPoint object, cast it to an IPEndPoint and use its Address property to access the IP address.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top