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.
It's a solution comparable to the accepted answer of TheSeeker. Though I think it's more readable:
If you want to get a free port in a specific range inorder to use it as local port /End point:
If you just want to give a starting port, and let it return to you the next tcp port available, use code like this:
Use a port number of 0. The TCP stack will allocate the next free one.
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.
Here is what I was looking for: