using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace IPCLib { public static class PortHelper { public static int FindAvailablePort(int startPort = 9000, int maxRetry = 100) { for (int i = 0; i < maxRetry; i++) { int port = startPort + i; try { var listener = new TcpListener(IPAddress.Loopback, port); listener.Start(); listener.Stop(); return port; } catch (SocketException) { } } throw new Exception("无法找到可用端口"); } } }