c# socket 判断端口是否被占用

来源:互联网 发布:蔡健雅 知乎 编辑:程序博客网 时间:2024/05/16 13:50

最近在搞 socket ,遇到端口占用的问题,程序需要自动检测端口是否占用,提醒服务端的端口更改。

于是,baidu下,发现居然都是,用try——catch  异常去判断是否占用,很是伤心啊。

现贴出下面代码,获取系统在已经使用的端口进行判断。

internal 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;        }


0 0
原创粉丝点击