C#: How to find an available port in a range of specific ports in TCP?

1.3k views Asked by At

How do I find start listening to a port in TCP protocol within a specific range?

For an example:

Check the ports from 6001 to 7000 until you find an available one
and start listening to it when found.
when someone else tries the same, he cannot listen to the same port.

Thank you.

1

There are 1 answers

0
Tango_Chaser On BEST ANSWER

I found a way to perform that:

private static int initialPort = 6001; // initial port to search from

public static void StartServerTCP()
{
    bool serverSet = false;
    while (!serverSet && initialPort <= 7000)
    {
        try
        {
            Console.WriteLine(Dns.GetHostName() + ": (Server:TCP) Trying to setup server at port: {0} [TCP]", initialPort);

            serverSocket.Bind(new IPEndPoint(GetIP(), initialPort));
            serverSocket.Listen(0);
            serverSocket.BeginAccept(AcceptCallback, null);
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine(Dns.GetHostName() + ": (Server:TCP) Server setup completed at port {0} [TCP]\n", initialPort);
            Console.ForegroundColor = ConsoleColor.Gray;
            serverSet = true;
        }
        catch (Exception)
        {
            Console.WriteLine("\n" + Dns.GetHostName() + ": (Server:TCP) Port <{0}> is busy, trying a different one\n", initialPort);
            initialPort++;
        }
    }
}