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

廉价感情. 提交于 2019-12-22 08:38:14

问题


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.

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

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

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

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

How can we do this on 64 bit Windows?


回答1:


You might get a good start via System.Net.NetworkInformation. In particular, 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. 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.

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.



来源:https://stackoverflow.com/questions/5400610/how-to-get-the-number-of-open-tcp-connections-held-by-a-certain-process-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!