Basic Scanning program to find open ports on host

In this blogs we will discuss about a basic scanning program to find open ports on host or target machine.

We have to make use of socket module and socket.connect_ex() function to create a basic scan program to find open ports on a host machine. socket.connect_ex() takes IP address and port as the parameters.

socket.connect_ex() function returns zero if found open port otherwise returns errno        (10060/10061). We can make use of this function to scan open ports on a target machine.

In the below code, we have a define list of ports to scan for url.

Step 1 Import Socket Module

Step 2 Determine host ip address

Step 3 Create a list of ports to scan

Step 4 Use socket.connect_ex() function to scan ports

Step 5 Displaying the result.  If result = 0 , display ‘Port is open’. If result is either 10060 or 10061, display ‘Port is closed’.

import socket
url =  ''
host = socket.gethostbyname(url)
list = [22,30,80,443,445,787]
for port in list:
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    result = s.connect_ex((host,port))
    if result == 0:
        print('Port %s is open'%port)
        print('Port %s is closed'%port)


Port 22 is closed
Port 30 is closed
Port 80 is open
Port 443 is open
Port 445 is closed
Port 787 is closed




Leave a Reply

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

You are commenting using your 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