TheSeeker TheSeeker - 1 year ago 120
C# Question

Find the next TCP port in .Net

I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open tcp port.

I know that TcpClient will assign a new client side port when I open a connection to a given server.

Is there a simple way to find the next open TCP port in .Net?

I need the actual number, so that I can build the string above, 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.

Answer Source

Here is what I was looking for:

static int FreeTcpPort()
  TcpListener l = new TcpListener(IPAddress.Loopback, 0);
  int port = ((IPEndPoint)l.LocalEndpoint).Port;
  return port;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download