How do I check with C if a port on my local machine (if required by passing an IP or interface, too), is in listen state? I don't want to connect to this port for checking because I don't want to irritate the service behind this port.
I want to use this to add the missing net.tcp.listen item to Zabbix.
EDIT - THIS IS THE REAL ANSWER:
The correct way is to read the socket tables:
/proc/net/tcp /proc/net/tcp6
They contain lines like:
sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
0: 00000000:1F40 00000000:0000 0A 00000000:00000000 00:00000000 00000000 101 0 4083927 1 f5d15240 750 0 0 2 -1
1: 00000000:2742 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1002 0 6100 1 decd76c0 750 0 0 2 -1
and can easily parsed for listening sockets (dst:00000000:0000). An strace on netstat shows that netstat works the same way.
Just try to open the port for listening. You will get an error.
There is no way you can steal a port from another process, so this will be safe, and of course easy to implement as it requires no additional code other than proper error handling.
The correct way is to read the socket tables:
/proc/net/tcp /proc/net/tcp6
They contain lines like:
sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
0: 00000000:1F40 00000000:0000 0A 00000000:00000000 00:00000000 00000000 101 0 4083927 1 f5d15240 750 0 0 2 -1
1: 00000000:2742 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1002 0 6100 1 decd76c0 750 0 0 2 -1
and can easily parsed for listening sockets (dst:00000000:0000). An strace on netstat shows that netstat works the same way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With