Home ยป Check if Network Port is Open using Python

Check if Network Port is Open using Python

In this example we check if a network port is open

Code

We have a function and we will check a website and the localhost

import socket


def is_network_port_open(hostname, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((hostname, port))
        sock.close()

        return True
    except socket.error:
        return False


is_open = is_network_port_open('google.com', 80)
print(is_open)  # True

is_open = is_network_port_open('127.0.0.1', 443)
print(is_open)  # False

 

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More