檢測端口是否被占用


        當我們要創建一個Tcp/Ip Server connection ,我們需要一個范圍在1000到65535之間的端口 。

但是本機一個端口只能一個程序監聽,所以我們進行本地監聽的時候需要檢測端口是否被占用。

        命名空間System.Net.NetworkInformation下定義了一個名為IPGlobalProperties的類,我們使用這個類可以獲取所有的監聽連接,然后判斷端口是否被占用,代碼如下:

 

public static bool PortInUse(int port)
{
    bool inUse = false;
            
    IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
    IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
            
    foreach (IPEndPoint endPoint in ipEndPoints)
    {
        if (endPoint.Port == port)
        {
            inUse = true;
            break;
        }
    }

    return inUse;
}

  我們使用HttpListner類在8080端口啟動一個監聽,然后測試是否可以被檢測出來,代碼如下:

 

static void Main(string[] args)
{
    HttpListener httpListner = new HttpListener();
    httpListner.Prefixes.Add("http://*:8080/");
    httpListner.Start();

    Console.WriteLine("Port: 8080 status: " + (PortInUse(8080) ? "in use" : "not in use"));

    Console.ReadKey();

    httpListner.Close();
}

 

 

 

 

 

 

 

 

           


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM