c# check if port is in use code example

Example: how to check if the server is listening on port in c#

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;
 }
// this function returns true only for local endpoints!!