How to Make a Port Scanner in Python using Socket Library

Abdou Rockikz · 05 aug 2019

Abdou Rockikz · 4 min read · Updated nov 2019 · Ethical Hacking

In this tutorial, you will be able to make your own port scanner in Python using socket library. The basic idea behind this simple port scanner is to try to connect to a specific host (website, server or any device connected to Internet/network) through a list of ports, if a successful connection has been established, that means the port is open.

For instance, when you loaded this web page, you have made a connection to this website on port 80, similarly, this script will try to connect to a host but on multiple ports. These kind of tools are useful for hackers and penetration testers, so don't use this tool to a host that you don't have permission to test!

Read AlsoHow to Brute-Force SSH Servers in Python.

Optionally, you need to install colorama module for fancy printing:

pip3 install colorama

Let's start by importing socket module:

import socket # for connecting
from colorama import init, Fore

# some colors
init()
GREEN = Fore.GREEN
RESET = Fore.RESET
GRAY = Fore.LIGHTBLACK_EX

Note: socket module is already installed in your machine, it is built in module in the Python standard library, so you don't have to install anything.

The socket module provides us with socket operations, functions for network-related tasks, etc. They are widely used on the Internet, as they are behind of any connection to any network. Any network communication goes through a socket, more details is at official Python documentation.

We will use colorama here just for printing in green colors whenever a port is open, and gray when it is closed.

Let's define the function that is responsible for determining whether a port is open:

def is_port_open(host, port):
    """
    determine whether `host` has the `port` open
    """
    # creates a new socket
    s = socket.socket()
    try:
        # tries to connect to host using that port
        s.connect((host, port))
        # make timeout if you want it a little faster ( less accuracy )
        # s.settimeout(0.2)
    except:
        # cannot connect, port is closed
        # return false
        return False
    else:
        # the connection was established, port is open!
        return True

s.connect((host, port)) function tries to connect the socket to a remote address (host,port), it will raise an exception when it fails to connect to that host, that is why we have wrapped that line of code into a try-except block, so whenever an exception is raised, that's an indication for us that the port is actually closed, otherwise it is open.

Now let's iterate over this function:

# get the host from the user
host = input("Enter the host:")
# iterate over ports, from 1 to 1024
for port in range(1, 1025):
    if is_port_open(host, port):
        print(f"{GREEN}[+] {host}:{port} is open      {RESET}")
    else:
        print(f"{GRAY}[!] {host}:{port} is closed    {RESET}", end="\r")

That's it, here is a screenshot when i tried to scan a local machine in my network:

Port Scanner

Now when you try to run it, you'll immediately notice that the script is quite slow, well, we can get away with that if we set a timeout of 200 milliseconds or so. However, this actually can reduce the accuracy of the reconnaissance, a better way to make it is to use Multi-Threading, don't worry if you don't know what that is, I already made a multi threading version of that scanner here.

Note that this script is intended for individuals to test their own devices and I will take no reponsibility if it is misused.

Happy Coding ♥

View Full Code
Sharing is caring!


Read Also





Comment panel

   
Comment system is still in Beta, if you find any bug, please consider contacting us here.