[ACCEPTED]-How to get a list of open sockets in Linux using C?-kernel

Accepted answer
Score: 19

Open and read the following:

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

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

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

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

Score: 4

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

Score: 3

In directory /proc/self/fd there are fake 7 symlinks giving you all your open file descriptors 6 - 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 5 using opendir, readdir() and then interrogate 4 them using readlink()

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

Score: 0

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

More Related questions