0

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.

Tango_Chaser
  • 319
  • 1
  • 3
  • 13
  • 1
    [Find the next TCP port in .Net](http://stackoverflow.com/questions/138043/find-the-next-tcp-port-in-net) – huse.ckr Jan 10 '17 at 09:23
  • 1
    You just need [this](http://stackoverflow.com/questions/570098/in-c-how-to-check-if-a-tcp-port-is-available) and a for loop – Lucifer Jan 10 '17 at 09:53

1 Answers1

2

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++;
        }
    }
}
Tango_Chaser
  • 319
  • 1
  • 3
  • 13