获取在C#中侦听给定端口的PID的最简单方法是什么?基本上,我想确保我的服务正在运行并侦听我提供的端口.如果有一种比解析netstat输出更简单的方法,那就太棒了.
这就是我的问题的答案。
如何在 C# 中列出绑定/使用的 TCP 端口。使用jro的修改代码
static void ListUsedTCPPort(ref ArrayList usedPort)
{
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners();
IEnumerator myEnum = tcpConnInfoArray.GetEnumerator();
while (myEnum.MoveNext())
{
IPEndPoint TCPInfo = (IPEndPoint)myEnum.Current;
usedPort.Add(TCPInfo.Port);
}
}
Run Code Online (Sandbox Code Playgroud)
原始问题。 这就是我使用 C# 列出 TCP 端口的方式。这是我在这个论坛中找到的修改后的代码(忘记了我到底是从哪里得到的。如果您是原始开发人员,请通知我,并在适当的时候注明积分。)
//List used tcp port
static void ListUsedTCPPort(ref ArrayList usedPort)
{
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
IEnumerator myEnum = tcpConnInfoArray.GetEnumerator();
while (myEnum.MoveNext())
{
TcpConnectionInformation TCPInfo = (TcpConnectionInformation)myEnum.Current;
usedPort.Add(TCPInfo.LocalEndPoint.Port);
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,结果与 TCPview(协议-TCP,本地端口)中列出的使用的 tcp 端口不同。顺便说一句,我确实知道这个列表在调用的确切时间使用了 TCP 端口。我做错了什么?