How to check port on remote host is accessible
This post shows how to validate remote host is accessible.
There are many solutions out there on how to check that port on a remote host is accessible. But we needed a solution that would not hang up.
Checking Remote Port
Here is the code that does the job:
1 2 3 4 5 6 7 8 9 10 11 12 import socket def port_is_open(host, port, timeout=0.5): result = False try: s = socket.create_connection((host, port), timeout) except socket.error as e: pass else: s.close() result = True return result
The check how it performs, we will use the timeit function shown here:
1 2 3 4 5 6 import time def timeit(func, *args, **kwargs): start_time = time.time() result = func(*args, **kwargs) print("returned %s in %s seconds" % (result, time.time() - start_time))
The result of checking that port on a remote host is accessible, and another that is not:
1 2 3 4 >>> timeit(port_is_open, "192.168.1.100", 22) returned True in 0.0007190704345703125 seconds >>> timeit(port_is_open, "192.168.1.70", 22) returned False in 0.5032269954681396 seconds
It cannot be easier, yea?!
Note: checking a port on remote host may be impacted by many things, predominantly how busy the network is and how busy are the involved hosts. Therefore, the timeout may need to be adjusted according to the operational environment.