views:

976

answers:

3

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.

+4  A: 

Use a port number of 0. The TCP stack will allocate the next free one.

Jerub
That does not work, since I need that actual #, not just 0. I need the number to build a string.
TheSeeker
+3  A: 

First open the port, then give the correct port number to the other process.

Otherwise it is still possible that some other process opens the port first and you still have a different one.

jan.vdbergh
Do you have a code sample to get such a tcp port as easy as possible?
TheSeeker
This is the way to do it. Gotta be careful, could be a race condition if more than one process opens the same port.
Mike Christiansen
+6  A: 

Here is what I was looking for:

static int FreeTcpPort()
{
  TcpListener l = new TcpListener(IPAddress.Parse("127.0.0.1"), 0);
  l.Start();
  int port = ((IPEndPoint)l.LocalEndpoint).Port;
  l.Stop();
  return port;
}
TheSeeker
And what happens if another process opens that port before you re-open it...?
Mike Christiansen
Then you will get an error of course, but that was not an issue for my context.
TheSeeker