S h o r t S t o r i e s

// Tales from software development

UdpClient – Getting the sender’s IP address

with 2 comments

I’ve just written a SYSLOG server and stumbled a little on trying to figure out where I could find the sender’s IP address for logging purposes.

I’m using a UdpClient with EnableBroadcast set to true and calling the BeginReceive and EndReceive methods to receive data asynchronously. A message can arrive from any client, so how do you identify the client IP address ? Logically, it should be associated with the message data but I couldn’t find anything that referenced it.

The mistake I’d made was following the misleading example code for the UdpClient BeginReceive method on MSDN. (The link is for the .NET 2.0 but the documentation is unchanged in later versions.) If you follow the code carefully you’ll see that the local IPEndPoint is stored in the UdpState object that is passed into the callback specified by BeginReceive. This IPEndpoint is then used on the call to EndReceive.

You’ll notice that this argument is passed by ref. Why ? My guess was that it’s because it’s populated by the EndReceive method. I experimented and confirmed it. So, the code in the example isn’t technically wrong but it is confused and misleading. Passing details of the local endpoint to EndReceive so that it can overwrite them with details of the remote end point isn’t very useful and probably wasn’t what the writer of the example intended.

I’d suggest creating a new empty IPEndPoint in the ReceiveCallback method and passing this into the EndReceive method:

IPEndPoint senderIpEndPoint = new IPEndPoint(0,0);
Byte[] messageBytes = u.EndReceive(ar, ref senderIpEndPoint);
string messageString = Encoding.ASCII.GetString(messageBytes);

Console.WriteLine("{0} {1}", senderIpEndPoint.Address.ToString(), messageString);



Written by Sea Monkey

March 11, 2010 at 8:00 pm

Posted in Development

Tagged with ,

2 Responses

Subscribe to comments with RSS.

  1. Trivial as this may be (after looking it up), I’m thankful you’ve BLogged this; saved me time! I saw a comment on StackOverflow in which somebody was asking the similar question for async mode UdpClient…


    December 5, 2014 at 10:02 pm

  2. Genius!

    Signer Upper

    April 28, 2016 at 9:52 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: