Testing if socket is accepting connections
nmap and netcat are great and easy ways to test if a socket is open and accepting connections:
nc -zv www.example.com 80 Connection to www.example.com 80 port [tcp/http] succeeded!
nmap -v example.com -Pn -p 80 Starting Nmap 7.80 ( https://nmap.org ) at 2021-03-02 06:23 CST Initiating Parallel DNS resolution of 1 host. at 06:23 Completed Parallel DNS resolution of 1 host. at 06:23, 0.17s elapsed Initiating Connect Scan at 06:23 Scanning example.com (188.8.131.52) [1 port] Discovered open port 80/tcp on 184.108.40.206 Completed Connect Scan at 06:23, 0.06s elapsed (1 total ports) Nmap scan report for example.com (220.127.116.11) Host is up (0.062s latency). Other addresses for example.com (not scanned): 2606:2800:220:1:248:1893:25c8:1946 PORT STATE SERVICE 80/tcp open http Read data files from: /usr/bin/../share/nmap Nmap done: 1 IP address (1 host up) scanned in 0.36 seconds
ncat and nmap may not always be installed, also the telnet package is usually no longer installed by default in most distributions.
These are some simple alternatives I have found useful to test connectivity:
Using openssl, the timeout is long and not configurable, but it does clearly state when able to open a socket with a message saying CONNECTED
openssl s_client -connect www.example.com:80 CONNECTED(00000003) 139935405417792:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:../ssl/record/ssl3_record.c:331: --- no peer certificate available --- No client certificate CA names sent --- SSL handshake has read 5 bytes and written 306 bytes Verification: OK --- New, (NONE), Cipher is (NONE) Secure Renegotiation IS NOT supported Compression: NONE Expansion: NONE No ALPN negotiated Early data was not sent Verify return code: 0 (ok) ---
You can also use the following simple python2 script to test if a port is accepting connection, the script takes two arguments host and port.
import socket import sys def test_socket(ip,port): s = socket.socket() try: s.settimeout(3) s.connect((ip,port)) except socket.error as msg: s.close() print 'could not open %s:%s %s' % (ip,port,msg) return(1) else: s.close() print '%s:%s is OK' % (ip,port) return(0) test_socket(sys.argv,int(sys.argv))
The script returns OK if its able to accept a connection
python test_socket.py www.example.com 80 www.example.com:80 is OK
Or returns the socket.error instead
python test_socket.py www.example.com 81 could not open www.example.com:81 timed out
python test_socket.py localhost 81 could not open localhost:81 [Errno 111] Connection refused