文章出處
文章列表
當我們要創建一個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(); }
文章列表
全站熱搜