Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux API to determine sockets owned by a process

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.

like image 773
Rob H Avatar asked Dec 30 '09 14:12

Rob H


People also ask

How can I tell what process is using a socket?

You can likely find the shared sockets by parsing /proc/net/tcp (and similar "files" for other protocols). There's some docs on /proc/net/tcp here. You would need to find the socket (perhaps by its IP addresses/port numbers ?) and parse out the inode number.

Can two processes use the same socket?

Two processes cannot bind (and listen) to the same unix socket.

What is socket command in Linux?

The ss (socket statistics) tool is a CLI command used to show network statistics. The ss command is a simpler and faster version of the now obsolete netstat command. Together with the ip command, ss is essential for gathering network information and troubleshooting network issues.


1 Answers

I think you first have to look through the open fds in /proc/*/fd, e.g.

4 -> socket:[11147] 

and then look for the referenced sockets (by the inode) in /proc/net/tcp (or /proc/net/udp), e.g.

12: B382595D:8B40 D5C43B45:0050 01 00000000:00000000 00:00000000 00000000  1000        0 11065 1 ffff88008bd35480 69 4 12 4 -1 
like image 166
cmeerw Avatar answered Oct 02 '22 15:10

cmeerw