Is there a Linux library that will enable me to tell what IP sockets are owned by what processes? I guess I'm looking for the programmatic equivalent of lsof -i
. Ultimately, I want to correlate packets seen through libpcap
to processes.
UPDATE: A couple of people have suggested using /proc/<pid>/net/tcp
and udp
, but on my system, the same data is shown for every process, so it doesn't help.
I think you first have to look through the open fds in /proc/*/fd, e.g.
and then look for the referenced sockets (by the inode) in /proc/net/tcp (or /proc/net/udp), e.g.
You could try running lsof with strace and see just which files in /proc it gets data from.
You can read them from proc filesystem. The 'files' you probably want to look at are found in
/proc/<pid>/net
(namely tcp, udp, unix)Here's some examples on using the proc filesystem
/proc/<pid>/net
is equivalent to/proc/net
for all processes in the same network namespace as you – in other words, it's "global" information.You can do what
lsof
andfuser
do, which is to iterate through both/proc/<pid>/fd/*
and/proc/net/*
looking for matching inodes. Quick demonstration:You can extend this to other protocols (I see ax25, ipx, packet, raw, raw6, udplite, udp6lite in
/proc/net/
too) or rewrite in a language of your choosing.The
/proc
filesystem provides details on each process, including networking information. Open socket information is listed in/proc/net/tcp
. The IPv6 sockets are listed separately in thetcp6
file. The socket information includes information such as the local and remote ports, and the socket inode number, which can be mapped back to the process by parsing the/proc/{pid}/fd/*
information.If you aren't familiar with the
/proc
filesystem, it is basically a virtual filesystem that allows the kernel to publish all sorts of useful information to user-space. The files are normally simple structured text files that are easy to parse.For example, on my Ubuntu system I used
netcat
for testing, and rannc -l -p 8321
to listen on port 8321. Looking at thetcp
socket information:The first line shows it is listening on all addresses to point 8321 (0x2081). The inode number is 26442, which we can use to look up the matching pid in
/proc/{pid}/fd/*
, which consists of a bunch of symlinks from the file handle number to the device. So if we look up the pid fornetcat
, and check itsfd
mapping:And there we see that file descriptor 3 in this process is mapped to the socket with inode 26442, just as we expect.
So obviously to build a complete map of sockets, you will need to first enumerate all the
/proc/**/fd/*
files, look up the socket symlinks, then match the socket inode against the tables from/proc/net/tcp
which has the endpoint information.This is the the way the
lsof
tool works (seelsof/dialects/linux/dsocket.c
for the implementation).I'd go to the source:
http://ubuntuforums.org/showthread.php?t=1346778