views:

601

answers:

1

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 IP level and collects data using recvfrom.

So I have address of remote host, local and remote ports. This is pretty cool, but I also need to have PID of local socket owner. So, is there any simple way to obtain such PID? The workaround is using GetTcpTable, GetUdpTable Or AllocateAndGetUdpExTableFromStack and AllocateAndGetTcpExTableFromStack (there is lot of differences in those functions between 2k, XP, XP SP2 and Vista) and to lookup result tables, but it seems inelegant and inefficient...

So is there any kind of "GetPIDOfSocket" function? The resolution sholud be WinAPI (no .net) only, as various languages can be used, eg C++, Delphi.

+2  A: 

Sorry to have to tell you, but using GetTcpTable or AllocateAndGetTcpExTableFromStack is not a workaround, it's actually how other netstat-type applications work. AFAIK there is no 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 SysInternals C source code for netstatp here. There's not a lot of it and it's well worth a look.

snowcrash09