Article purpose
This article features a short illustration of how to determine if a network port is already in use.
Introduction
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.
Sample source code
This article is accompanied by sample source code in a Visual Studio project which is available for download here.
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;
break;
}
}
return inUse;
}
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/" );
httpListner.Start();
Console .WriteLine("Port: 8080 status: " + (PortInUse(8080) ? "in use" : "not in use" ));
Console .ReadKey();
httpListner.Close();
}
0 Responses to “C# How to: Check if a Tcp Port is in use”