在C#中,要使用TcpClient或连接到套接字,我如何首先检查机器上的某个端口是否空闲?
更多信息:这是我使用的代码:
TcpClient c;
//I want to check here if port is free.
c = new TcpClient(ip, port);
发布于 2009-02-20 17:17:30
由于您正在使用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.
发布于 2010-11-12 21:59:19
谢谢你的建议。我需要相同的功能,但在服务器端用来检查Port是否正在使用,所以我将其修改为以下代码。
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;
}
发布于 2010-05-08 15:37:23
谢谢你的回答,jro。我不得不调整它以适应我的使用。我需要检查端口是否正在被监听,而不是必须处于活动状态。为此,我替换了
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
使用
IPEndPoint[] objEndPoints = ipGlobalProperties.GetActiveTcpListeners();.
我迭代了端点数组,检查没有找到我的端口值。
https://stackoverflow.com/questions/570098
复制相似问题