SoFunction
Updated on 2025-03-08

C# Simple example of detecting whether the port is occupied

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

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

A class named IPGlobalProperties is defined under the namespace. We use this class to get all listening connections and then determine whether the port is occupied. The code is as follows:

Copy the codeThe code is as follows:

public static bool PortInUse(int port)
{
    bool inUse = false;

    IPGlobalProperties ipProperties = ();
    IPEndPoint[] ipEndPoints = ();

    foreach (IPEndPoint endPoint in ipEndPoints)
    {
        if ( == port)
        {
            inUse = true;
            break;
        }
    }

    return inUse;
}

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

Copy the codeThe code is as follows:

static void Main(string[] args)
{
    HttpListener httpListner = new HttpListener();
    ("http://*:8080/");
    ();

    ("Port: 8080 status: " + (PortInUse(8080) ? "in use" : "not in use"));

    ();

    ();
}