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

最近在搞 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;
        }


posted @ 2014-11-20 10:46  mendel  阅读(3100)  评论(0编辑  收藏  举报