C#:如何在TCP中的特定端口范围内查找可用端口?

时间:2017-01-10 09:20:25

标签: c# sockets tcp ports

如何在特定范围中的 TCP协议中开始收听端口?

举个例子:

  

检查6001到7000的端口,直到找到可用的端口为止   并在找到时开始收听   当别人尝试的时候   同样,他不能听同一个港口。

谢谢。

1 个答案:

答案 0 :(得分:1)

我找到了一种方法来执行:

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