如下:

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);
        }
    }
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-06
  • 2022-12-23
  • 2021-10-08
  • 2022-12-23
  • 2021-08-20
  • 2022-12-23
猜你喜欢
  • 2021-10-19
  • 2021-05-18
  • 2021-12-25
  • 2022-02-07
  • 2022-12-23
  • 2022-12-23
  • 2021-06-29
相关资源
相似解决方案