c#检测端口是否被占用的简单实例
时间:2022-08-10 01:45:49
当我们要创建一个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)
{
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();
Console.WriteLine("Port: 8080 status: " + (PortInUse(8080) ? "in use" : "not in use"));
Console.ReadKey();
httpListner.Close();
}
标签:c#,检测端口,占用
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
java在网页上面抓取邮件地址的方法
2023-10-01 19:18:21
android利用消息机制获取网络图片
2023-07-24 09:46:57
![](https://img.aspxhome.com/file/2023/2/85962_0s.jpg)
springcloud配置ssh的问题及解决方法
2023-11-03 15:48:11
![](https://img.aspxhome.com/file/2023/7/58757_0s.jpg)
C++实现日期类的示例详解
2022-07-29 04:19:24
![](https://img.aspxhome.com/file/2023/2/104362_0s.png)
spring mvc实现文件上传并携带其他参数的示例
2023-11-20 11:54:06
android TextView中识别多个url并分别点击跳转方法详解
2023-06-21 04:42:32
c#通用登录模块分享
2023-07-21 15:54:31
详解Java中二叉树的基础概念(递归&迭代)
2022-04-04 13:40:17
![](https://img.aspxhome.com/file/2023/6/122336_0s.jpg)
如何将IDEA打成jar包并在windows后台运行
2022-02-27 01:36:57
![](https://img.aspxhome.com/file/2023/6/61546_0s.png)
C# 向Word中设置/更改文本方向的方法(两种)
2023-01-12 21:37:33
java 中 System.out.println()和System.out.write()的区别
2021-09-17 04:30:52
C++编程中的函数指针初步解析
2023-05-04 23:08:24
![](https://img.aspxhome.com/file/2023/8/122568_0s.jpg)
Java中基于Shiro,JWT实现微信小程序登录完整例子及实现过程
2023-07-05 15:01:42
![](https://img.aspxhome.com/file/2023/1/69071_0s.png)
C# XML基础入门小结(XML文件内容增删改查清)
2022-10-18 17:12:02
Java通过在主循环中判断Boolean来停止线程的方法示例
2022-07-18 09:15:03
解决问题:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources
2023-11-23 23:40:39
![](https://img.aspxhome.com/file/2023/1/59871_0s.jpg)
Java BigDecimal中divide方法案例详解
2021-12-31 07:00:29
基于Spring@Autowired注解与自动装配详谈
2022-01-14 09:38:49
Java泛型映射不同的值类型详解及实例代码
2023-07-29 00:20:52
java对指定目录下文件读写操作介绍
2023-01-26 11:53:17