I need to count amount of bytes sent and received from the network by various applications. First I thought about using LSP, but there is a lot of applications that do not use LSP at all (SMB for example). This is why I have written a small sniffer. This application works on the IP level and collects data using recvfrom.
So I have the address of the remote host, local and remote ports. This is pretty cool, but I also need to have the PID of the local socket owner. So, is there a simple way to obtain such PID?
The workaround is using GetTcpTable, GetUdpTable Or AllocateAndGetUdpExTableFromStack and AllocateAndGetTcpExTableFromStack (there are a lot of differences in those functions between Windows 2000, Windows XP, Windows XP SP2 and Windows Vista) and to lookup result tables, but it seems inelegant and inefficient...
So is there a kind of A "GetPIDOfSocket" function? The resolution should be Win32 (no .NET) only, as various languages can be used, e.g. C++ and Delphi.
Using GetTcpTable
or AllocateAndGetTcpExTableFromStack
is not a workaround. It's actually how other netstat-type applications work.
As far as I know, there isn't any Win32 "GetPIDOfSocket"
function. Your only option is to poll using the port table functions. But at least you can code it up yourself and don't have to spawn the netstat process.
See the Sysinternals C source code for netstatp
here. There's not a lot of it and it's well worth a look.