简体   繁体   English

如何获取.NET中某个进程持有的开放TCP连接数

[英]How to get the number of open TCP connections held by a certain process in .NET

I need to monitor the number of open TCP connections held by a single process on a 64 bit Windows 7 machine from .NET 4.0. 我需要在.NET 4.0上监视64位Windows 7计算机上单个进程持有的打开TCP连接数。

This article describes the undocumented Win32 API method "AllocateAndGetTcpExTableFromStack" that accomploshes this task on 32 bit windows: 本文介绍了在32位窗口上完成此任务的未记录的Win32 API方法“AllocateAndGetTcpExTableFromStack”:

http://www.codeproject.com/KB/IP/iphlpapi.aspx?display=Print http://www.codeproject.com/KB/IP/iphlpapi.aspx?display=Print

But this fails on my machine (presumably because I am on 64 bit) with: 但这在我的机器上失败了(大概是因为我在64位):

Unable to find an entry point named 'AllocateAndGetTcpExTableFromStack' in DLL 'iphlpapi.dll'. 无法在DLL“iphlpapi.dll”中找到名为“AllocateAndGetTcpExTableFromStack”的入口点。

How can we do this on 64 bit Windows? 我们如何在64位Windows上执行此操作?

You might get a good start via System.Net.NetworkInformation . 您可以通过System.Net.NetworkInformation获得良好的开端。 In particular, IPGlobalProperties.GetActiveTcpConnections . 特别是IPGlobalProperties.GetActiveTcpConnections

However, you will find that this library does not expose the PID, so there is no way to narrow it down by the particular process associated with each connection. 但是,您会发现此库不公开PID,因此无法通过与每个连接关联的特定进程来缩小它。 I'm guessing it will be much easier to simply parse the output of a console netstat -ano into a collection of managed objects, and use a simple LINQ query to pull out the specific connections you need based on process ID. 我猜测简单地将控制台netstat -ano的输出解析为托管对象集合会更容易,并使用简单的LINQ查询根据进程ID提取所需的特定连接。 However, I wouldn't recommend this if you're going to be doing it often, as it would be a very slow method. 但是,如果您经常这样做,我不建议这样做,因为这将是一个非常慢的方法。

You may also try the PInvoke for GetExtendedTcpTable() in the DLL you reference above. 您也可以在上面引用的DLL中尝试PInvoke for GetExtendedTcpTable() I don't have my x64 box to test, but it could be a simple deprecation of the particular function you're trying to call. 我没有测试我的x64盒子,但它可能是你试图调用的特定功能的简单弃用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM