在C#中,要获取处于“已建立”状态的端口,你可以使用System.Net.NetworkInformation
命名空间中的IPGlobalProperties
类和TcpConnectionInformation
类。以下是一个示例代码,展示了如何获取所有处于“已建立”状态的TCP连接端口:
using System;
using System.Net.NetworkInformation;
class Program
{
static void Main()
{
// 获取IP全局属性
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
// 获取所有TCP连接信息
TcpConnectionInformation[] tcpConnections = ipGlobalProperties.GetActiveTcpConnections();
Console.WriteLine("处于已建立状态的端口:");
foreach (TcpConnectionInformation tcpConnection in tcpConnections)
{
if (tcpConnection.State == TcpState.Established)
{
Console.WriteLine($"本地端口: {tcpConnection.LocalEndPoint.Port}, 远程端口: {tcpConnection.RemoteEndPoint.Port}");
}
}
}
}
Listen
、SynSent
、SynReceived
、Established
、FinWait1
、FinWait2
、CloseWait
、Closing
、LastAck
、TimeWait
和Closed
。其中,“已建立”状态表示连接已经成功建立,可以进行数据传输。通过上述方法和注意事项,你可以有效地在C#中获取处于“已建立”状态的端口,并应用于各种实际场景中。
领取专属 10元无门槛券
手把手带您无忧上云