//获取一个空闲端口号,80和8080端口优先 public static int GetAvailablePort() { IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); IPEndPoint[] endpoints= ipGlobalProperties.GetActiveTcpListeners(); bool is80free = true; bool is8080free = true; foreach (var ep in endpoints) { if (ep.Port == 80) { is80free = false; } if (ep.Port == 8080) { is8080free = false; } if (!is8080free && !is80Ofree) break; } if (is80free) return 80; if (is8080free) return 8080; TcpListener tcp = new TcpListener(new IPEndPoint(IPAddress.Any, 0)); tcp.Start(); int port = (tcp.LocalEndpoint as IPEndPoint).Port; tcp.Stop(); return port; }
获取一个空闲端口号
最新推荐文章于 2024-04-10 19:07:20 发布