public static int GetAvailablePort(PortPoolRange range, IEnumerable<int> exludes = null) { var excluded = (exludes ?? new List<int>()).ToList(); IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); for (int port = range.StartPort; port <= range.EndPort; port++) { var portIsInUse = tcpConnInfoArray.Any(tcpPort => tcpPort.LocalEndPoint.Port == port); int port1 = port; if (!portIsInUse && !excluded.Any(p => p == port1)) { return port; } } throw new InvalidOperationException(string.Format("Could not find any TCP port in range {0}", range.Format())); }
static int GetAvailableHttpsPort(params int[] exclusions) { var range = new PortPoolRange(44330, 100); var excluded = new List<int>(); if (exclusions != null && exclusions.Any()) { excluded.AddRange(exclusions); } return TcpHelper.GetAvailablePort(range, excluded); }
static int GetAvailableHttpPort(int? exclude = null) { var range = new PortPoolRange(45000, 100); var excluded = new List<int>(); if (exclude.HasValue) { excluded.Add(exclude.Value); } return TcpHelper.GetAvailablePort(range, excluded); }