首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在C#中,如何检查TCP端口是否可用?

在C#中,如何检查TCP端口是否可用?
EN

Stack Overflow用户
提问于 2009-02-20 15:53:38
回答 13查看 224.9K关注 0票数 132

在C#中,要使用TcpClient或连接到套接字,我如何首先检查机器上的某个端口是否空闲?

更多信息:这是我使用的代码:

代码语言:javascript
复制
TcpClient c;
//I want to check here if port is free.
c = new TcpClient(ip, port);
EN

回答 13

Stack Overflow用户

回答已采纳

发布于 2009-02-20 17:17:30

由于您正在使用TcpClient,这意味着您正在检查打开的TCP端口。在System.Net.NetworkInformation名称空间中有很多优秀的对象。

使用IPGlobalProperties对象获取TcpConnectionInformation对象的数组,然后可以查询端点IP和端口。

代码语言:javascript
复制
 int port = 456; //<--- This is your value
 bool isAvailable = true;

 // Evaluate current system tcp connections. This is the same information provided
 // by the netstat command line application, just in .Net strongly-typed object
 // form.  We will look through the list, and if our port we would like to use
 // in our TcpClient is occupied, we will set isAvailable to false.
 IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
 TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

 foreach (TcpConnectionInformation tcpi in tcpConnInfoArray)
 {
   if (tcpi.LocalEndPoint.Port==port)
   {
     isAvailable = false;
     break;
   }
 }

 // At this point, if isAvailable is true, we can proceed accordingly.
票数 240
EN

Stack Overflow用户

发布于 2010-11-12 21:59:19

谢谢你的建议。我需要相同的功能,但在服务器端用来检查Port是否正在使用,所以我将其修改为以下代码。

代码语言:javascript
复制
 private bool CheckAvailableServerPort(int port) {
    LOG.InfoFormat("Checking Port {0}", port);
    bool isAvailable = true;

    // Evaluate current system tcp connections. This is the same information provided
    // by the netstat command line application, just in .Net strongly-typed object
    // form.  We will look through the list, and if our port we would like to use
    // in our TcpClient is occupied, we will set isAvailable to false.
    IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
    IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners();

    foreach (IPEndPoint endpoint in tcpConnInfoArray) {
        if (endpoint.Port == port) {
            isAvailable = false;
            break;
        }
    }

    LOG.InfoFormat("Port {0} available = {1}", port, isAvailable);

    return isAvailable;
}
票数 16
EN

Stack Overflow用户

发布于 2010-05-08 15:37:23

谢谢你的回答,jro。我不得不调整它以适应我的使用。我需要检查端口是否正在被监听,而不是必须处于活动状态。为此,我替换了

代码语言:javascript
复制
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

使用

代码语言:javascript
复制
IPEndPoint[] objEndPoints = ipGlobalProperties.GetActiveTcpListeners();.  

我迭代了端点数组,检查没有找到我的端口值。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/570098

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档