Failed to listen on prefix http://localhost:portnumber because it conflicts with an existing registration on the machine

When creating a TCP/IP server connection on a Windows based platform you can specify a port number ranging from 1000 to 65535. It would seem unlikely that two applications executing at the same time will both attempt to open the same port number, in reality it happens quite often. It is advisable to first determine if a port is already in use before attempting to start a server connection listening on that port.


Active Tcp Listeners

The System.Net.NetworkInformation namespace defines an IPGlobalProperties class. Using IPGlobalProperties we can determine the IPEndPoint every server connection listens on for incoming connections. Listed below is a code snippet detailing the PortInUse method.

 public static bool PortInUse(int  port)
     bool inUse = false;
     IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
     IPEndPoint [] ipEndPoints = ipProperties.GetActiveTcpListeners();

     foreach(IPEndPoint endPoint in ipEndPoints)
         if  (endPoint.Port == port)
             inUse = true;

     return  inUse;

or if you want to use Linq expressions:

private bool PortInUse(ushort servicePort)
            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();

            return ipEndPoints.Any(endpoint => endpoint.Port == servicePort);

The PortInUse method determines all active server connections, then proceeds to iterate an Array of IPEndPoint objects comparing port numbers to the method’s only parameter.

The Implementation
The PortInUse method is implemented in a Console based application. First the sample source starts up an instance of the HttpListner class on port 8080. The HttpListner definition is followed by determining if port 8080 is in fact being used.

 static  void  Main(string [] args)
     HttpListener  httpListner = new  HttpListener ();
     httpListner.Prefixes.Add("http://*:8080/" );

     Console .WriteLine("Port: 8080 status: "  + (PortInUse(8080) ? "in use" : "not in use" ));

     Console .ReadKey();


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.