26

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?

30

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.

  • Thank you! Upvoted and accepted. I do see a socket showing up in lsof as "unix 0xffff88002704d380 0t0 1423733559 socket", how do I dig into what 0xffff88002704d380 is? – benhsu Oct 14 '15 at 12:30
  • 1
    "unix 0xfff ..." seems like the kernel memory address of a unix_sock structure. This structure contains a pointer to your socket-end point. Take a look at grep -rni ffff88002704d380 /proc. somewhere under /proc/ may lie your answer, cat your file grep found. But dont pin me down on this... May be horrible wrong here. – pidi Oct 14 '15 at 13:58
  • lsof reads other information about the socket from /proc/net/tcp, /proc/net/tcp6, /proc/net/udp, and so on depending on socket type. – Jesin Nov 15 '17 at 22:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.