zoukankan      html  css  js  c++  java
  • 获取本机可用端口

    如下:

    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);
            }
        }
    }
  • 相关阅读:
    hotel管理
    MySQL数据库的学习
    搭建纸飞机
    二维码
    Linux 的安装
    AngularJS学习笔记
    css3部分知识点
    如何处理数据
    jq跨域在127.0.0.1:8020上的写法
    AJAX请求方式
  • 原文地址:https://www.cnblogs.com/yao2yao4/p/3258392.html
Copyright © 2011-2022 走看看