C#指定指定端口是否已經被占用的代碼

xg48 9年前發布 | 4K 次閱讀 C#

下面的C#代碼定義了一個函數用于判斷指定的端口是否已經被占用。
代碼轉自: http://www.cnblogs.com/smiler/

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;

}</pre>
下面的范例代碼占用了8080端口,然后用上面定義的函數檢測端口是否被占用

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

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

Console.ReadKey();

httpListner.Close();

}</pre>

 本文由用戶 xg48 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!