Test connection to a port without actually connecting to it

0

I have a python socket server (single-threaded, accepts only one connection) running somewhere.

I connect to that port and do my things.

How can I detect whether port is open or closed without making any connection? I mean, I don't want to close the port to see if it is open or not :-)

I already tried nc -zvv ip port but this closes the script (because it actually connects to the port).

vfsoraki

Posted 2014-06-25T11:14:51.527

Reputation: 1 927

Modify the script so that it doesn't exit when the connection is closed. – gronostaj – 2014-06-25T11:26:30.280

So no other way? Does this behavior also happen when using a port scanner like nmap? – vfsoraki – 2014-06-25T11:48:35.477

Answers

1

Use a port-scanning tool like nmap. When run with sufficient privileges (on Linux the cap_net_raw privilege is necessary, "root" on other Unix systems) the tool has several scan modes that do not involve completing the TCP handshake.

The default scan mode when privileged is "TCP SYN scan" (the -sS option), which tries to start a TCP handshake but immediately resets it. This way, the program is not informed about a connection attempt because there was no connection.

To scan specific ports, add the -p <ports> option.

$ sudo nmap --reason -sS -p 22,53,79,80 localhost
PORT    STATE  SERVICE REASON
22/tcp  open   ssh     syn-ack
79/tcp  open   finger  syn-ack
143/tcp closed imap    reset
443/tcp closed https   reset

user1686

Posted 2014-06-25T11:14:51.527

Reputation: 283 655