c is a simple instance that detects whether a port is occupied

  • 2020-05-26 10:03:31
  • OfStack

When we want to create an Tcp/Ip Server connection, we need a port between 1000 and 65535.

However, only one program can listen on one port of the machine, so we need to check whether the port is occupied when we listen locally.

The namespace System.Net.NetworkInformation defines a class named IPGlobalProperties. We can use this class to get all the listening connections and then determine whether the port is occupied. The code is as follows:


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

We use HttpListner class to start a listener on port 8080, and then test whether it can be detected. The code is as follows:


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


Related articles: