In this article we will see how to check if a port of a remote host is open or not with Python.
This check requires the creation of a socket towards the remote host on the specified port indicating a timeout in seconds which allows us to avoid useless waiting in the request.
import socket def check_port(host='127.0.0.1', port=80, timeout=2): sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.settimeout(timeout) try: sck.connect((host, int(port))) sck.shutdown(socket.SHUT_RDWR) return True except: return False finally: sck.close()
If the port is open, the boolean value
True is returned. In case of exceptions, such as a connection timeout or other network-level errors, the value
False is returned. To optimize resource management, the
finally block closes the socket in both cases.