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!
On Solaris you can use
pfiles(1)
to do this:For Linux, this is more complex (gruesome):
00000000:0016
is0.0.0.0:22
. Here's the equivalent output fromnetstat -a
:The easiest thing to do is
On Linux (I don't know about Solaris). This will give you a log of all of the system calls made. It's a lot of output, some of which will be relevant. Take a look at the files in the /proc file system that it's opening. This should lead you to how netstat does it. Indecently, ltrace will allow you to do the same thing through the c library. Not useful for you in this instance, but it can be useful in other circumstances.
If it's not clear from that, then take a look at the source.
Take a look at these answers which thoroughly explore the options available:
For Linux, have a look at the
/proc/net
directory (for example,cat /proc/net/tcp
lists your tcp connections). Not sure about Solaris.Some more information here.
I guess netstat basically uses this exact same information so i don't know if you will be able to speed it up a whole lot. Be sure to try the netstat '-an' flags to NOT resolve ip-adresses to hostnames realtime (as this can take a lot of time due to dns queries).
Why don't you look at the source code of netstat and see how it get's the information? It's open source.
I don't know how often you need to poll, or what you mean with "expensive", but with the right options both
netstat
andlsof
run a lot faster than in the default configuration.Examples:
shows only listening tcp sockets, and omits the (slow) name resolution that is on by default.
omits all blocking operations, name resolution, and limits the selection to IPv4 tcp sockets on port 80.