C# 查看電腦連接埠使用狀態

來源:互聯網
上載者:User

標籤:

using System.Net.NetworkInformation;/// <summary>/// 擷取第一個可用的連接埠號碼/// </summary>/// <returns></returns>public static int GetFirstAvailablePort(){    int MAX_PORT = 6000; //系統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;}

C# 查看電腦連接埠使用狀態

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.