如下:
using System; using System.Collections.Generic; using System.Linq; using System.Net.NetworkInformation; namespace ConsoleApplication2 { public static class AvailablePort { /// <exception cref="Exception"></exception> public static int GetFirstAvailablePort() { const int MAX_PORT = 65535; const int BEGIN_PORT = 5000; for (var i = BEGIN_PORT; i < MAX_PORT; i++) { if (PortIsAvailable(i)) { return i; } } throw new Exception("No Available Port."); } private static IEnumerable<int> PortIsUsed() { var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); var ipsTCP = ipGlobalProperties.GetActiveTcpListeners(); var ipsUDP = ipGlobalProperties.GetActiveUdpListeners(); var tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); return ipsTCP.Select(ep => ep.Port) .Concat(ipsUDP.Select(ep => ep.Port)) .Concat(tcpConnInfoArray.Select(conn => conn.LocalEndPoint.Port)) .ToList(); } private static bool PortIsAvailable(int port) { return PortIsUsed().All(p => p != port); } } }