『QQ:1353814576』

C# 判断端口是否正在被其他程序使用着


C# 判断端口是否正在被其他程序使用着

通过查看当前所有使用这段端口 从中匹配是否有对应的端口号 存在即已被使用 反之则没被使用

        /// <summary>
        /// 已经激活端口列表是否包含了指定端口
        /// </summary>
        /// <param name="port">查询的端口号</param>
        /// <returns></returns>
        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{
       //端口空置
}