UnixDroid

Lesson 5 of 12 · 8 min

Build a Python port scanner with sockets

A port scanner is the hello-world of ethical hacking tools. Build a working one in about 15 lines with Python's built-in socket module.

A port scanner is the 'hello world' of ethical hacking tools — and the fastest way to understand how computers expose services to a network. You'll build a working one in about 15 lines using Python's built-in socket module. Run it only against your own machine or lab.

What a port actually is

A single server runs many services at once — a website, email, SSH. Ports are the numbered doors that keep them apart: web on 80, HTTPS on 443, SSH on 22. Scanning asks each door, politely, 'is anyone home?'

The core idea: try to connect

Checking a port is just attempting a TCP connection. If it succeeds, the port is open.

import socket

def scan(host, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(1)
    result = s.connect_ex((host, port))   # 0 means success
    s.close()
    return result == 0

connect_ex returns 0 when the port is open and an error code otherwise — so it never crashes, it just reports.

Scanning a range of ports

target = '127.0.0.1'
for port in range(20, 1025):
    if scan(target, port):
        print(f'[+] Port {port} is open')

Run it against your own machine and you'll see exactly which services you're exposing.

PieceJob
socket.socket(...)Creates a TCP connection object
settimeout(1)Don't wait forever on a dead port
connect_exTry to connect; return 0 if open
range(20, 1025)The well-known port range to check

Tip: settimeout matters more than anything else. Without it, one unresponsive port can hang your scan for a minute. With it, a closed port fails fast and the whole scan flies.

Why it's slow (and what's next)

This scanner checks one port at a time, waiting for each. Against 1,000 ports that's painfully slow — in the next lesson you'll make it dozens of times faster with threads, and have it report what each open service is.

Try it yourself
  1. Run the scanner against 127.0.0.1 and note which ports are open.
  2. Change the range to scan only 20-100 and time how long it takes.
  3. Add a line that prints 'Scan complete' with the total number of open ports found.
No Linux machine? Practise in the free online terminal

Quick check

Which socket method tries to connect and returns 0 when a port is open, instead of raising an error?

Need a hint?

It is like connect, but ends in underscore-ex.

Finished this lesson?

Done lessons keep your daily streak going 🔥

0 day streak

0 lessons done

best 0 days

Log in to keep your streak on every device →