小编典典

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

c#

在C#中使用TcpClient或通常连接到套接字,如何首先检查计算机上某个端口是否空闲?

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

TcpClient c;
//I want to check here if port is free.
c = new TcpClient(ip, port);

阅读 513

收藏
2020-05-19

共1个答案

小编典典

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

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


 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.
2020-05-19