• 获取可用端口(转载)


    http://blog.csdn.net/hnpzhili/article/details/6234906 

    /// <summary>
            /// 获取第一个可用的端口号
            /// </summary>
            /// <returns></returns>
            public static int GetFirstAvailablePort()
            {
                int MAX_PORT = 65535; //系统tcp/udp端口数最大是65535            
                int BEGIN_PORT = 5000;//从这个端口开始检测

                for (int i = BEGIN_PORT; i < MAX_PORT; i++)
                {
                    if (PortIsAvailable(i)) return i;
                }

                return -1;
            }

            /// <summary>
            /// 获取操作系统已用的端口号
            /// </summary>
            /// <returns></returns>
            public static IList PortIsUsed()
            {
                //获取本地计算机的网络连接和通信统计数据的信息
                IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();

                //返回本地计算机上的所有Tcp监听程序
                IPEndPoint[] ipsTCP = ipGlobalProperties.GetActiveTcpListeners();

                //返回本地计算机上的所有UDP监听程序
                IPEndPoint[] ipsUDP = ipGlobalProperties.GetActiveUdpListeners();

                //返回本地计算机上的Internet协议版本4(IPV4 传输控制协议(TCP)连接的信息。
                TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

                IList allPorts = new ArrayList();
                foreach (IPEndPoint ep in ipsTCP) allPorts.Add(ep.Port);
                foreach (IPEndPoint ep in ipsUDP) allPorts.Add(ep.Port);
                foreach (TcpConnectionInformation conn in tcpConnInfoArray) allPorts.Add(conn.LocalEndPoint.Port);

                return allPorts;
            }

            /// <summary>
            /// 检查指定端口是否已用
            /// </summary>
            /// <param name="port"></param>
            /// <returns></returns>
            public static bool PortIsAvailable(int port)
            {
                bool isAvailable = true;

                IList portUsed = PortIsUsed();

                foreach (int p in portUsed)
                {
                    if (p == port)
                    {
                        isAvailable = false; break;
                    }
                }

                return isAvailable;

            } 

  • 相关阅读:
    判断一个数组是不是一维数组
    XML5个转义符:<,>,&,”,©;的转义字符分别如下: &lt; &gt;&amp; &quot; &apos;
    linux crontab & 每隔10秒执行一次
    微信企业号-根据code获取成员信息(过期code)
    Namespace declaration statement has to be the very first statement in the script-去除bom头
    去掉一个字符前面的全部0
    检查一个数字是否为个位数
    nginx配置location总结及rewrite规则写法
    QT 4.7支持中文(QT4.7)(中文)(makeqpf)
    【转】vlc android 代码编译
  • 原文地址:https://www.cnblogs.com/bobzhangfw/p/2440380.html
Copyright © 2020-2023  润新知