views:

366

answers:

4

Find the next TCP port in .Net says how to do this in raw .net, but not how to safely to this with WCF.

In my unit tests, I need to use the NetTcpBinding, I do not wish to hard code the port it is using.

Therefore how can I get the NetTcpBinding to automatically choose a free port when used in my ServiceHost?

How can I get it to tell me the port (or full endpoint address) it has chosen?

Or how can I using .NET find a few port that is valid for a server to bind to?


Given that my bounty did not lead to any new answers, I think we can assume there is no good answer.

+1  A: 

Here's what I do: start with a random port in range 1025-2000 (range chosen arbitrarily). I try to bind it and if it fails I catch the exception. Then I go one port up (port = port % 2000 + 1025) until I wrap. I no port is bound, I give up failing the test.

Marcin
+1 that's pretty much what I do. Works well, though I start at around 5000..
Len Holgate
how do you stop the windows firewall openning up it's UK each time you try a port?
Ian Ringrose
uh, I dunno about this firewall thingy; my devel machine has no firewall on it, as it is within firewalled network
Marcin
Ian, I don't have a firewall configured on the machines that I develop network applications on or on my build machines, so it's not an issue.
Len Holgate
+1  A: 

when using a random high port you can generate collisions with other server processes that want to start after your program. just use zero as the port number and let the os care about reservations (/etc/services on unix, don´t know how windows handles it).

sascha
sorry I only care about windows
Ian Ringrose
+2  A: 

Set the port to zero. That allows the OS to pick an available port for you. If you need to determine which port was used, you can query that from the socket after it has been bound locally.

Remy Lebeau - TeamB
how to I get the socket from the NetTcpBinding WCF, if I pass in a port of 0?
Ian Ringrose
A: 

At present I believe this is not possible, thanks for everyone that provided work a rounds.

Ian Ringrose