Build a Simple Python Port Scanner: Step‑by‑Step Guide

This article explains how to create a Python‑based network port scanner that probes a target host, uses sockets and multithreading to detect open TCP ports, and provides clear usage instructions, sample code, and optional enhancements for faster or more comprehensive scanning.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Build a Simple Python Port Scanner: Step‑by‑Step Guide

Overview

Network scanning tools discover open ports and services. Python's standard library enables lightweight port scanners.

Implementation Principle

The scanner iterates over a range of TCP ports, attempts to establish a TCP connection, and treats a successful connection as an open port. The socket module provides the network I/O, while threading enables parallel scans.

Class‑Based Scanner

import socket
import threading

class PortScanner:
    def __init__(self, host):
        self.host = host
        self.open_ports = []

    def scan(self, port):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(1)
            sock.connect((self.host, port))
            sock.close()
            self.open_ports.append(port)
        except:
            pass

    def scan_range(self, start, end):
        for port in range(start, end + 1):
            t = threading.Thread(target=self.scan, args=[port])
            t.start()

    def scan_all(self):
        self.scan_range(1, 65535)
        while threading.active_count() > 1:
            pass
        for port in sorted(self.open_ports):
            print(f"Port {port} is open")

if __name__ == "__main__":
    scanner = PortScanner("localhost")
    scanner.scan_all()

Usage

Replace "localhost" with the target IP or hostname.

Run the script; it scans ports 1‑65535 and prints open ports.

Argument‑Parser Version

This variant accepts host and port range via command‑line arguments.

import socket
import argparse

def scan_port(host, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)
        sock.connect((host, port))
        print(f"Port {port} is open")
        sock.close()
    except:
        pass

def scan_range(host, start_port, end_port):
    for port in range(start_port, end_port + 1):
        scan_port(host, port)

def main():
    parser = argparse.ArgumentParser(description="Python Port Scanner")
    parser.add_argument("-H", "--host", type=str, required=True,
                        help="Hostname or IP address to scan")
    parser.add_argument("-p", "--port", type=str, required=True,
                        help="Port range, e.g., 1-65535")
    args = parser.parse_args()
    start_port, end_port = map(int, args.port.split("-"))
    scan_range(args.host, start_port, end_port)

if __name__ == "__main__":
    main()

Run example:

python scanner.py -H localhost -p 1-65535

Installation

Python 3.7 or newer is required. Execute the script from a terminal; root/administrator privileges may be needed for privileged ports.

Extensibility

The basic scanner can be extended with:

More threads or a thread pool to improve performance.

UDP probing using socket.SOCK_DGRAM.

Asynchronous I/O (e.g., asyncio) for higher concurrency.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythonnetwork securitythreadingSocketPort ScannerArgument Parsing
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.