[python]Test connection with socket module

This is the code snippet that checks if a specific port is listening on the target server or not, if the port could not be reached and does not exist the socket module throws a timeout exception or ConnectionRefusedError.

from socket import socket, timeout as _timeout, AF_INET, SOCK_STREAM

ERRORS = TimeoutError, ConnectionRefusedError, _timeout
def has_service(address, port=22, timeout=2.0):
    with socket(AF_INET, SOCK_STREAM) as s:
        s.settimeout(timeout)
        try:
            s.connect((address, port))
            return True
        except ERRORS:
            return False

Example if I want to check if a server has port 80.

from nettools import has_service

print(has_service("www.google.com", port=80))

This will return a true because this is a valid website.

Another test is to test if there is a ssh server, I have an Eve-Ng server which has port 80 and 22.

from nettools import has_service

print(has_service("192.168.1.214"))

This will return as true because port 22 exists, if the port does not exist the function returns false.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s