欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

c#檢測端口是否被占用的簡單實例

 更新時間:2013年12月06日 15:54:05   作者:  
這篇文章主要介紹了c#檢測端口是否被占用的簡單實例,有需要的朋友可以參考一下

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

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

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

復(fù)制代碼 代碼如下:

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端口啟動一個監(jiān)聽,然后測試是否可以被檢測出來,代碼如下:

復(fù)制代碼 代碼如下:

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

相關(guān)文章

最新評論