namespace Example; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net.NetworkInformation; public static class FreePortDetector { private static readonly List ReservedPorts = []; public static bool IsPortFree(int port) { if (ReservedPorts.Contains(port)) { return false; } else { // http://stackoverflow.com/a/570126/107625 var globalProperties = IPGlobalProperties.GetIPGlobalProperties(); var informations = globalProperties.GetActiveTcpListeners(); return informations.All(information => information.Port != port); } } public static void RemovePort(int port) { ReservedPorts.Remove(port); } public static int GetFreePort() { if (int.TryParse(ConfigurationManager.AppSettings[@"webserver.listenPort"], out var alt) && alt > 0) { alt += ReservedPorts.Count; if (IsPortFree(alt)) { ReservedPorts.Add(alt); return alt; } } // -- for (var i = 0; i < 10; ++i) { var port = Random.Shared.Next(9000, 15000); if (IsPortFree(port)) { ReservedPorts.Add(port); return port; } } throw new("No free port could be found."); } }