C#:如何在 TCP 的特定端口范围内查找可用端口?
C#: How to find an available port in a range of specific ports in TCP?
如何在特定范围内找到开始侦听TCP协议中的端口?
举个例子:
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.
谢谢。
我找到了执行该操作的方法:
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++;
}
}
}
如何在特定范围内找到开始侦听TCP协议中的端口?
举个例子:
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.
谢谢。
我找到了执行该操作的方法:
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++;
}
}
}