c#检测端口是否被占用的简单实例。
static void Main(string[] args)
{
HttpListener httpListner = new HttpListener();
httpListner.Prefixes.Add("http://*:8080/");
httpListner.Start(); // www.jbxue.com
当我们要创建一个Tcp/Ip Server connection ,我们需要一个范围在1000到65535之间的端口 。
但是本机一个端口只能一个程序监听,所以我们进行本地监听的时候需要检测端口是否被占用。
命名空间System.Net.NetworkInformation下定义了一个名为IPGlobalProperties的类,我们使用这个类可以获取所有的监听连接,然后判断端口是否被占用,代码如下:
复制代码代码如下:
public static bool PortInUse(int port)
{
bool inUse = false;
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
foreach (IPEndPoint endPoint in ipEndPoints)
{ // www.jbxue.com
if (endPoint.Port == port)
{
inUse = true;
break;
}
}
{
bool inUse = false;
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
foreach (IPEndPoint endPoint in ipEndPoints)
{ // www.jbxue.com
if (endPoint.Port == port)
{
inUse = true;
break;
}
}
return inUse;
}
使用HttpListner类在8080端口启动一个监听,然后测试是否可以被检测出来,代码如下:
复制代码代码如下:
static void Main(string[] args)
{
HttpListener httpListner = new HttpListener();
httpListner.Prefixes.Add("http://*:8080/");
httpListner.Start(); // www.jbxue.com
Console.WriteLine("Port: 8080 status: " + (PortInUse(8080) ? "in use" : "not in use"));
Console.ReadKey();
httpListner.Close();
}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步