前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#指定指定端口是否已经被占用的代码

C#指定指定端口是否已经被占用的代码

原创
作者头像
用户7108768
修改2021-11-02 14:50:58
8560
修改2021-11-02 14:50:58
举报
代码语言:javascript
复制
ublic 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;

}</pre> 

 下面的范例代码占用了8080端口,然后用上面定义的函数检测端口是否被占用
static void Main(string[] args)
{
    HttpListener httpListner = new HttpListener();
    httpListner.Prefixes.Add("http://*:8080/&quot;);
    httpListner.Start();

Console.WriteLine("Port: 8080 status: " + (PortInUse(8080) ? "in use" : "not in use"));

Console.ReadKey();

httpListner.Close();

}</pre> 

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档