views:

668

answers:

2

How can I determine an un-used port to start a WCF ServiceHost to host a localhost web server on?

I'm currently starting my service up statically on http://localhost:XXXX where XXXX is a static value in my code.

I'd like to replace the XXXX with a GetUnusedPort() call...

Any thoughts?

+1  A: 

Why not let the user choose which port they want to host the service on? For example, add a value to your application's configuration file that gets passed to your ServiceHost. You could also try randomly generating a port number and test to see if it's open, then repeat the process if another application is already using it.

David Brown
A: 

Best I could find was the try until you find an open one option...

http://forums.devshed.com/net-development-87/c-how-to-determine-if-a-port-is-in-use-371148.html

 public static bool TryPortNumber(int port)
 {
  try
  {

   using (var client = new System.Net.Sockets.TcpClient(new System.Net.IPEndPoint(System.Net.IPAddress.Any, port)))
   {
    return true;
   }
  }
  catch (System.Net.Sockets.SocketException error)
  {
   if (error.SocketErrorCode == System.Net.Sockets.SocketError.AddressAlreadyInUse /* check this is the one you get */ )
    return false;
   /* unexpected error that we DON'T have handling for here */
   throw error;
  }
 }
Jason Jarrett