Information Security 4 min read

Building a Simple Python Port Scanner in 20 Lines

This tutorial explains how to create a lightweight Python port scanner using only standard libraries, covering required imports, command‑line host input, a full‑range port loop with socket connections, result handling, and runtime measurement, all within a concise 20‑line script.

IT Services Circle
IT Services Circle
IT Services Circle
Building a Simple Python Port Scanner in 20 Lines

Port scanning is a practical technique used not only in information security but also in everyday operations, and implementing your own scanner in Python allows customization and addition of personal features.

Required libraries : The script uses only Python standard libraries—socket for low‑level network connections, argparse for command‑line argument parsing, sys for system interaction, and time for measuring execution duration.

Host argument : Using argparse, the script accepts a host name or IP address as the first positional argument, accessible via args.host .

Port scanning loop : It iterates over the full port range 1‑65535, creates a TCP socket for each port, sets a 1‑second timeout, and calls sock.connect_ex((args.host, port)) . If the result is 0, the port is reported as open; sockets are closed after each attempt. KeyboardInterrupt is caught to allow graceful termination.

Complete script :

import socket
import argparse
import sys
import time

parser = argparse.ArgumentParser()
parser.add_argument('host')
args = parser.parse_args()
start = time.time()

try:
    for port in range(1, 65536):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)
        result = sock.connect_ex((args.host, port))
        if result == 0:
            print("Port: {} Open".format(port))
        sock.close()
except KeyboardInterrupt:
    sys.exit()

end = time.time()
print(f"Scanning completed in: {end-start:.3f}s")

Running the script (which consists of exactly 20 lines of code) prints each open port and the total scanning time, as demonstrated by the accompanying screenshots.

cliPythonTutorialNetwork SecuritySocketport scanning
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

login 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.