获取本机可用端口

如下:

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

 

posted on 2013-08-14 20:07  yao2yao4  阅读(363)  评论(0编辑  收藏  举报

导航