Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On linux, how to check if port is in listen state without trying to connect

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.

like image 791
Daniel Avatar asked May 31 '10 09:05

Daniel


2 Answers

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.

like image 104
Peter Tillemans Avatar answered Oct 27 '22 00:10

Peter Tillemans


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.

like image 23
Daniel Avatar answered Oct 26 '22 23:10

Daniel