C# How to: Check if a Tcp Port is in use

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 namespace defines an class. Using we can determine the 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 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 class on port 8080. The 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();
 }
 
Advertisements

0 Responses to “C# How to: Check if a Tcp Port is in use”



  1. Leave a Comment

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s




Dewald Esterhuizen

Blog Stats

  • 437,835 hits

Enter your email address to follow and receive notifications of new posts by email.

Join 204 other followers

Archives

Twitter feed


%d bloggers like this: