当咱们要建立一个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(); }