如何获得按一定程序在.NET中保持打开的TCP连接数如何获得、连接数、程序、按一定

2023-09-03 20:38:57 作者:红了眼睛〞湿了眶

我需要监控的单个进程在64位的Windows 7机器上的.NET 4.0保持打开的TCP连接数。

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.

本文介绍了未公开的Win32 API的方法AllocateAndGetTcpExTableFromStack的accomploshes这个任务在32位Windows:

This article describes the undocumented Win32 API method "AllocateAndGetTcpExTableFromStack" that accomploshes this task on 32 bit windows:

HTTP://www.$c$cproject。 COM / KB / IP / iphlpapi.aspx?显示=打印

但这个失败对我的机器(presumably,因为我在64位):

But this fails on my machine (presumably because I am on 64 bit) with:

无法找到名为切入点   在AllocateAndGetTcpExTableFromStack   DLLIPHLPAPI.DLL。

Unable to find an entry point named 'AllocateAndGetTcpExTableFromStack' in DLL 'iphlpapi.dll'.

我们如何才能做到这一点在64位Windows?

How can we do this on 64 bit Windows?

推荐答案

您可能会得到通过的 System.Net.NetworkInformation 。尤其是, IPGlobalProperties.GetActiveTcpConnections 。

You might get a good start via System.Net.NetworkInformation. In particular, IPGlobalProperties.GetActiveTcpConnections.

不过,你会发现,这个库不公开的PID,所以没有办法通过与每个连接关联的特定进程,以缩小它。我猜它会更容易简单地分析控制台的netstat -ano 的输出为管理对象的集合,并使用一个简单的LINQ查询拉出具体的连接,您需要根据进程ID。但是,我不建议这一点,如果你要经常这样做,因为这将是一个非常缓慢的方法。

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. 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. However, I wouldn't recommend this if you're going to be doing it often, as it would be a very slow method.

您也可以尝试的PInvoke为 GetExtendedTcpTable()在您引用上面的DLL。我没有我的64箱进行测试,但它可能是你试图调用特定功能的简单去precation。

You may also try the PInvoke for GetExtendedTcpTable() in the DLL you reference above. 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.