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

c#檢測(cè)端口是否被占用的簡(jiǎn)單實(shí)例

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

當(dāng)我們要?jiǎng)?chuàng)建一個(gè)Tcp/Ip Server connection ,我們需要一個(gè)范圍在1000到65535之間的端口 。

但是本機(jī)一個(gè)端口只能一個(gè)程序監(jiān)聽(tīng),所以我們進(jìn)行本地監(jiān)聽(tīng)的時(shí)候需要檢測(cè)端口是否被占用。

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

復(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類(lèi)在8080端口啟動(dòng)一個(gè)監(jiān)聽(tīng),然后測(cè)試是否可以被檢測(cè)出來(lái),代碼如下:

復(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)文章

最新評(píng)論