PID from socket number on Windows?

元气小坏坏 提交于 2019-11-30 19:00:50

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/819708/pid-from-socket-number-on-windows

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