How to tie a network connection to a PID without using lsof or netstat?

jac_no_k picture jac_no_k · May 8, 2009 · Viewed 21.2k times · Source

Is there a way to tie a network connection to a PID (process ID) without forking to lsof or netstat?

Currently lsof is being used to poll what connections belong which process ID. However lsof or netstat can be quite expensive on a busy host and would like to avoid having to fork to these tools.

Is there someplace similar to /proc/$pid where one can look to find this information? I know what the network connections are by examining /proc/net but can't figure out how to tie this back to a pid. Over in /proc/$pid, there doesn't seem to be any network information.

The target hosts are Linux 2.4 and Solaris 8 to 10. If possible, a solution in Perl, but am willing to do C/C++.

additional notes:

I would like to emphasize the goal here is to tie a network connection to a PID. Getting one or the other is trivial, but putting the two together in a low cost manner appears to be difficult. Thanks for the answers to so far!

Answer

8jean picture 8jean · May 8, 2009

I don't know how often you need to poll, or what you mean with "expensive", but with the right options both netstat and lsof run a lot faster than in the default configuration.
Examples:

netstat -ltn

shows only listening tcp sockets, and omits the (slow) name resolution that is on by default.

lsof -b -n -i4tcp:80

omits all blocking operations, name resolution, and limits the selection to IPv4 tcp sockets on port 80.