在C#中,要使用TcpClient或一般情况下连接到套接字,我如何首先判断机器上的某个端口是否空闲?
more info:个 这是我使用的代码:
TcpClient c;
//I want to check here if port is free.
c = new TcpClient(ip, port);
在C#中,要使用TcpClient或一般情况下连接到套接字,我如何首先判断机器上的某个端口是否空闲?
more info:个 这是我使用的代码:
TcpClient c;
//I want to check here if port is free.
c = new TcpClient(ip, port);
由于您使用的是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.