tags:

views:

336

answers:

1

If I create a socket using

var socket = new UdpClient(0,AddressFamily.InterNetwork);

How do I then find the port of the socket?

I'm probably being daft, but I'm not having luck in MSDN/Google (probably because it is 4:42 on a Friday and the sun is shining).

Background:

What I want to do is find an open port, and then report to another process to forward messages to me on that port. There may be multiple clients, so I don't want to used a fixed port.

Thanks.

+4  A: 

UdpClient is a wrapper around the Socket class which exposes the endpoint it's bound to through the LocalEndPoint property. Since you're using an UDP/IP client it's an IPEndPoint which has the desired Port property:

int port = ((IPEndPoint)socket.Client.LocalEndPoint).Port;
dtb
thanks. I'll implement this first thing Monday morning. What I was missing was the cast to IPEndPoint, so then intellisense didn't help me any. :(
rathkopf