获取随机可用TCP端口号(C#)

获取随机可用TCP端口号(C#)

最近开启MQTT服务,需要获取随机可用的TCP端口号,需要两步:

  • 通过System.Net.NetworkInformation中的GetIPGlobalProperties,获取所有可用的端口号;

    /// <summary>
    /// 获取所有可用的TCP端口
    /// </summary>
    /// <param name="startPort"></param>
    /// <returns></returns>
    public static List<int> GetAllAvailableTCPPort(int startPort = 1000)
    {
        //提供本地计算机有关网络连接信息
        IPGlobalProperties iPGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
        //获取可用的TCP监听终结点信息
        IPEndPoint[] iPEndPoints = iPGlobalProperties.GetActiveTcpListeners();
        return iPEndPoints.Where(q => q.Port >= startPort && q.Port <= MaxPort).Select(q => q.Port).ToList();
    }
    
  • 采用随机数的方法,判断特定范围(1024, 65535)的可用端口。

    /// <summary>
    /// 获取随机可用端口号
    /// </summary>
    /// <returns></returns>
    public static int GetRandomPort()
    {
        List<int> portList = new List<int>();
        portList = GetAllAvailableTCPPort();
    
        int port = 0;
        bool IsRandomOK = true;
        Random random = new Random((int)DateTime.Now.Ticks);
        while (IsRandomOK)
        {
            port = random.Next(1024, 65535);
            IsRandomOK = portList.Contains(port);
        }
        return port;
    }
    
    // 设置最大端口号
    private const int MaxPort = 65535;
    
posted @ 2022-12-21 17:31  Logan1418  阅读(528)  评论(0)    收藏  举报