using System.Net; using System.Net.Sockets; namespace Ads.Desktop; public static class ConnectionPorts { /// Find a free loopback port without terminating another application's listener. public static int Allocate(int first, IEnumerable reserved) { if (first is < 1024 or > 65535) throw new InvalidOperationException("起始端口范围为 1024–65535。"); var excluded = reserved.ToHashSet(); excluded.Add(5037); for (var port = first; port <= 65535; port++) { if (excluded.Contains(port)) continue; var probe = new TcpListener(IPAddress.Loopback, port); try { probe.Server.ExclusiveAddressUse = true; probe.Start(); return port; } catch (SocketException) { } finally { probe.Stop(); } } throw new InvalidOperationException("没有可用的本地端口,请修改起始端口或释放其他连接。"); } }