您的位置:首页 > 编程语言 > C#

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

2014-11-20 10:46 411 查看
最近在搞 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: