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



免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM