Linux interface to get connected IPs

linuxnetworking

Is there an interface to get the currently connected IPs and their state in Linux? I am aware of ss and netstat, but I want to use /proc/ or some other "official" kernel interface that already has them (if it exists). If it doesn't exist where would I start to get this information? Basically, I need an interface that has this information so I can retrieve it programmatically.

Best Answer

Besides ss and netstat I currently don't know any other tools that I'd recommend.

For how to get this information:

If you man netstat, you can see at the section FILES some listed files that netstat uses to collect its information.

Among these, there are /proc/net/tcp and /proc/net/udp.

If you cat /proc/net/tcp you can see various information about tcp connections on your system.

A sample output would be

sl local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode
0: 0101007F:0035 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 11190 1 0000000000000 000 100 0 0 10 0
1: 8700A8C0:91FC 0F02000A:15B3 01 00000000:00000000 02:00000AF6 00000000  1000        0 5565254 2 00000000000 00000 46 4 13 10 -1

rem_address here is the IP you are looking for. I don't know much about it, but I think st gives you information about the current state. 0A should mean LISTEN, 01 means ESTABLISHED.

Decoding a local_address or rem_address is rather easy, 8700A8C0:8F76 for example:

Format: hex(rev_ip):hex(port)

87 -> 135
00 -> 0
A8 -> 168
C0 -> 192
:8F76 -> 36726

=> 192.168.0.135, Port 36726

More information about the /proc/net directory is here.

More information about the presented data is here.

A related SO thread is also here.

Related Question