Home » Check if Network Port is Open using Python

Check if Network Port is Open using Python

Spring Framework Basics Video Course
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]
Oracle Java Certification
1 Year Subscription
Java SE 11 Programmer II [1Z0-816] Practice Tests

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