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();
 }
 

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



  1. Leave a Comment

Leave a comment




Dewald Esterhuizen

Blog Stats

  • 869,810 hits

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

Join 228 other subscribers

Archives

RSS SoftwareByDefault on MSDN

  • An error has occurred; the feed is probably down. Try again later.