C# 判断端口是否正在被其他程序使用着
通过查看当前所有使用这段端口 从中匹配是否有对应的端口号 存在即已被使用 反之则没被使用
////// 已经激活端口列表是否包含了指定端口 /// /// 查询的端口号 /// public bool PortAssociatedProcess(int port) { IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); IPEndPoint[] ipendpoints = ipendpoints = properties.GetActiveTcpListeners(); int count = ipendpoints.Count(e => e.Port == port); return count>0; }
调用例子
bool IsUsed = PortAssociatedProcess(1433); if(IsUsed) { //端口已被使用 }else{ //端口空置 }