Python program to check if a network port is open
In this Python programming article, you are going to learn how to check if a particular port is open. We are using
socket.connect_ex() to check if a network port is open. Before going into programming first let’s understand what is Socket Programming and some basic terminology of socket programming.
Before we go forward, we first need to know about socket programming.
What is Socket Programming
Socket Programming is a way of connecting two nodes on a network in order to communicate with each other. One socket or node listens to a particular port at an IP address and the other socket reaches out to the other port for creating a connection. In simple terms, they are called client-server programming. They are the backbones behind web browsing.
Python has a socket library for implementing socket programming. Let’s make a simple socket
import socket as sock s = sock.socket(sock.AF_INET, sock.SOCK_STREAM)
Here we made a socket and passed two parameters. The first parameter is AF_INET refers to address-family ipv4 and the second parameter SOCK_STREAM refers to the connection-oriented TCP protocol.
Checking if the network port is open using Python programming
Below are given steps to perform our task in Python:
1) First import the socket library as sock.
2) Create a socket object by calling sock.socket(family, type) with the family set to sock.AF_INET and the type set to SOCK_STREAM.
3) Create a destination as a tuple containing the IP address and the desired port number.
4) To check port is open call sock.connect_ex(destination) which returns 0 if the port is open, 1 if the port is close.
5) After checking the port is open, then socket by using socket.close().
import socket as sock create_socket = sock.socket(sock.AF_INET, sock.SOCK_STREAM) destination = ("127.0.0.1", 80) result = create_socket.connect_ex(destination) if result == 0: print("Port is open") else: print("Port is not open") create_socket.close()
Port is not open