How to find out more about socket files in /proc/fd

networkingprocsocket

Looking in /proc/$mypid/fd/, I see these files

lrwx------ 1 cm_user cm_user 64 Oct 14 03:21 0 -> /dev/pts/36 (deleted)
lrwx------ 1 cm_user cm_user 64 Oct 14 03:21 3 -> socket:[1424055856]
lrwx------ 1 cm_user cm_user 64 Oct 14 03:21 4 -> socket:[1424055868]
lrwx------ 1 cm_user cm_user 64 Oct 14 03:21 5 -> socket:[1424055882]

Because I have access to the code, I know these sockets are tied to TCP connections (one is a connection to port 5672 on some machine, another is a connection to port 3306 on some other machine), but I want to know which socket is tied to which connection. How can I do that?

More generally, how can I ask the OS what is at the other end of the socket?

Best Answer

Command lsof

A good option might be lsof. As man lsof states it is handy for obtaining information about open files such as Internet sockets or Unix Domain sockets.


Using it

At first, get an overview about /proc/$PID/fd/ and the listed socket numbers.
For example, socket:[14240] might interest you.

Then use lsof -i -a -p $PID to print a list of all network files $PID uses.

  • -i produces a list of network files belonging to a user or process

  • -a logically combines or AND's given parameters

  • -p $PID selects info only about your process

A typical output for my browser running with a PID of 2543 might be:

COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
browser 2543 pidi   55u  IPv4  14240      0t0  TCP  pidi.router.lan:55038->stackoverflow.com:https (ESTABLISHED)

and more similar lines.

Great! Now take a closer look at the DEVICE column. It matches our previously listed socket from /proc/$PID/fd/!
And thanks to the NAME section we can say what the other end of our socket is.

In a real world run you might get a good amount of output, but just filter or grep for your socket of interest.

I'm pretty sure one could combine all commands, but that should be enough to get you started.