檢測端口是否被佔用

        當咱們要建立一個Tcp/Ip Server connection ,咱們須要一個範圍在1000到65535之間的端口 。web

可是本機一個端口只能一個程序監聽,因此咱們進行本地監聽的時候須要檢測端口是否被佔用。測試

        命名空間System.Net.NetworkInformation下定義了一個名爲IPGlobalProperties的類,咱們使用這個類能夠獲取全部的監聽鏈接,而後判斷端口是否被佔用,代碼以下:spa

 

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端口啓動一個監聽,而後測試是否能夠被檢測出來,代碼以下:code

 

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();
}
相關文章
相關標籤/搜索