8

Is there a way to get a list of all open sockets ( socket address or socket descriptor ) in Linux using C in user-space or kernel?

Thank you

Misha M
  • 10,979
  • 17
  • 53
  • 65

4 Answers4

19

Open and read the following:

/proc/net/tcp - a list of open TCP sockets

/proc/net/udp - a list of open UDP sockets

/proc/net/raw - a list all the "raw" sockets

These are like "regular" files that you open and read with a filehandle and will give you all the information you could possibly need about each socket.

Spooky
  • 2,966
  • 8
  • 27
  • 41
Shane C. Mason
  • 7,518
  • 3
  • 26
  • 33
4

In directory /proc/self/fd there are fake symlinks giving you all your open file descriptors - sockets give something like:

lrwx------ 1 root root 64 2009-05-08 07:45 4 -> socket:[4921]
lrwx------ 1 root root 64 2009-05-08 07:45 5 -> socket:[4918]
lrwx------ 1 root root 64 2009-05-08 07:45 6 -> socket:[5395]

Iterate them using opendir, readdir() and then interrogate them using readlink()

If you know that FD 4 is a socket, you can then call getsockname() on it to get the local address family, address etc, if bound.

MarkR
  • 62,604
  • 14
  • 116
  • 151
  • This does not work for all sockets. Mostly, I see my terminals on here. With multiple connections open, not all sockets are visible. Good tool non-the-less to have in addition to what Shane Mason noted. Thank you. – Misha M May 09 '09 at 05:26
4

This program may be useful for you and demonstrates how to parse the /net/proc/* files sockstat.c

nmuntz
  • 1,158
  • 2
  • 11
  • 22
  • Thanks for the example. I was just going to go through the /proc/self/fd and check which links are sockets and generate the list that way. I'll post an update with my solution here. Thanks again – Misha M May 08 '09 at 22:09
  • Link seems to no longer work, though google searches for it finds several copies. – Stéphane Nov 28 '12 at 23:40
0

The raw data can be found at /proc/net/tcp, /proc/net/udp, etc. Refer to the header at the first line for a (terse) description.

bdonlan
  • 224,562
  • 31
  • 268
  • 324