Port scanning is one of the most fundamental skills in network security. Whether you are auditing your own infrastructure or learning how attackers think, understanding how port scanners work is essential. In this tutorial, we will build a multithreaded TCP port scanner in pure Python — no external libraries required.

What You Will Learn

  • How TCP socket connections work at the code level
  • Using Python's socket and threading modules
  • Why scanning too slowly is a problem — and how threads fix it
  • Ethical and legal boundaries of port scanning

The Basic Approach

A port scanner attempts to open a TCP connection to a target IP address on a range of ports. If the connection succeeds, the port is open. If it is refused or times out, the port is closed or filtered.

Step 1: Single-Port Scan Function

import socket

def scan_port(target, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(1)
    result = s.connect_ex((target, port))
    s.close()
    return result == 0

connect_ex returns 0 on success. We set a 1-second timeout so the script does not hang on filtered ports.

Step 2: Multithreaded Scanner

import socket
import threading
from queue import Queue

target = "127.0.0.1"
queue = Queue()
open_ports = []
lock = threading.Lock()

def worker():
    while not queue.empty():
        port = queue.get()
        if scan_port(target, port):
            with lock:
                open_ports.append(port)
        queue.task_done()

# Queue ports 1-1024
for port in range(1, 1025):
    queue.put(port)

threads = []
for _ in range(100):
    t = threading.Thread(target=worker)
    t.start()
    threads.append(t)

for t in threads:
    t.join()

print(f"Open ports: {sorted(open_ports)}")

Why 100 Threads?

Without threads, scanning 1,024 ports sequentially at 1 second each would take over 17 minutes. With 100 workers, the same scan finishes in roughly 10-15 seconds. You can tune this number based on your system and network conditions.

Ethical Use Only

Only scan systems you own or have explicit written permission to test. Unauthorized scanning may violate computer misuse laws in your jurisdiction.

Next Steps

  • Add banner grabbing to identify services running on open ports
  • Implement SYN stealth scanning using scapy
  • Parse nmap-style target ranges (e.g. 192.168.1.0/24)

Happy scanning — responsibly.