How to get ports on which we can start tcp server on windows? C# .NET

Szynkie _ 0 Reputation points
2023-05-05T15:05:57.6+00:00

I wanted to get information if the port is available to set up a new TcpListener on it using c#. I have tried to use IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners() and IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections() methods, but there are more ports that I cannot start a tcp listener on. Most of them are reserved by windows, see https://superuser.com/questions/1486417/unable-to-start-kestrel-getting-an-attempt-was-made-to-access-a-socket-in-a-way or https://ardalis.com/attempt-made-to-access-socket/. enter image description here

but there are also some that are not in use, not reserved and we still cannot start TcpListener on them, in my case: enter image description here

Second solution that I have tried was trying to start a TcpListener and see if it will throw an exception, sth like:

static bool CanStartServer(int port)

{

    var ip = IPAddress.Any;

    var tcpServer = new TcpListener(ip, port);

    try

    {

        tcpServer.Start();

    }

    catch (SocketException e)

    {

        return false;

    }

    tcpServer.Stop();

    ip = IPAddress.IPv6Any;

    tcpServer = new TcpListener(ip, port);

    try

    {

        tcpServer.Start();

    }

    catch (SocketException e)

    {

        return false;

    }

    tcpServer.Stop();

    return true;

}

but there are some cases when it starts a tcp server on already taken port and ip address, eg I can start tcpListener on port 6500 and ip 0.0.0.0, but I have already had a server:
Obraz

Can you please explain it to me and tell me how to get all information I need to know which port can I use?

Windows 10
Windows 10
A Microsoft operating system that runs on personal computers and tablets.
10,955 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,489 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 59,056 Reputation points
    2023-05-05T17:13:23.31+00:00
    0 comments No comments