tags:

views:

338

answers:

2

Is there a way, using C#, to determine if a port is available? I'd like to check before I start up a WCF ServiceHost instance using a port that's already used :-)

+3  A: 

You cannot determine if a port is available. You can only determine

  1. That you have control of a port
  2. That a port was available at some point in the past

Unless you control the port by having a particular socket bound and listening on the port, it's possible for another process to come along and take control of the port.

The only reliable way to know if a port is available is to attempt to listen on it. If you succeed then the port is available and you have control. Otherwise you know that at some point in the past and potentially the present, the port was controlled by another entity.

JaredPar