如何在C#中确定Windows进程使用的TCP端口

7

有没有一种受控的类/方法可以提供特定Windows进程使用的TCP端口号?

我真正需要的是以下CMD行的.NET等效版本:

netstat -ano |find /i "listening"
2个回答

15

除 PID 外,看看这个:

IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();

IPEndPoint[] endPoints = ipProperties.GetActiveTcpListeners();
TcpConnectionInformation[] tcpConnections = 
    ipProperties.GetActiveTcpConnections();

foreach (TcpConnectionInformation info in tcpConnections)
{
    Console.WriteLine("Local: {0}:{1}\nRemote: {2}:{3}\nState: {4}\n", 
        info.LocalEndPoint.Address, info.LocalEndPoint.Port,
        info.RemoteEndPoint.Address, info.RemoteEndPoint.Port,
        info.State.ToString());
}
Console.ReadLine();

来源: 使用C#编写Netstat

更深入的研究带来了这个: 使用C#构建你自己的netstat.exe。 这个项目使用P/Invoke调用GetExtendedTcpTable,并使用与netstat相同的结构。


6
也要获取PID吗? - Revious
1
“Build your own netstat” 的链接已经失效。@Konamiman的评论中有一个有效的链接:https://timvw.be/2007/09/09/build-your-own-netstatexe-with-c/ - EddPorter
@EddPorter 更新: https://web.archive.org/web/20150520071202/http://www.timvw.be/2007/09/09/build-your-own-netstatexe-with-c/ - user3625699
1
网站仍然在线,只是更像一个点:https://timvw.be/2007/09/09/build-your-own-netstat.exe-with-c 但它可以使用WinAPI工作。 - Mr. Squirrel.Downy

2

1
页面未找到 :( - Misaz
这是一个有效的链接:https://timvw.be/2007/09/09/build-your-own-netstat.exe-with-c/ - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接