October 31, 2026
Building a Python TCP Port Scanner From Scratch: A Practical Cybersecurity Guide
Learn how TCP port scanning works, build a multithreaded scanner using Python, identify common services, and export network assessmentβ¦
By Sreedev Sreekumar
8 min read
Learn how TCP port scanning works, build a multithreaded scanner using Python, identify common services, and export network assessment results to CSV.
Introduction
Every network-connected system uses communication endpoints through which applications exchange data. Web servers, remote administration tools, and database services commonly rely on network ports to accept connections.
Understanding which ports are open on a system is an important part of network reconnaissance and security assessment.
This is where TCP port scanning becomes useful.
In this project, I built a beginner-friendly Python TCP Port Scanner to explore how network port scanning works and how Python can be used to automate basic network discovery.
The scanner allows users to examine a target hostname or IP address, scan a custom range of TCP ports, identify common service names, and save scan results to a CSV file.
The project also incorporates multithreading to improve scanning efficiency and provides a summary of the scan, including the number of ports examined, open ports discovered, and execution time.
In this article, I'll explain the networking concepts behind the project, discuss its architecture, demonstrate how to use the tool, and explore its limitations.
The objective is not just to build a scanning utility, but to understand the networking concepts and programming techniques behind it.
1. Understanding TCP Ports
A port is a logical communication endpoint used by applications running on network-connected systems.
TCP and UDP each maintain separate port spaces, with port numbers ranging from 0 to 65535.
Different network services commonly use particular port numbers.
Some examples of commonly used TCP ports include:
- Port 22 β SSH: Secure remote administration.
- Port 53 β DNS: Domain name resolution.
- Port 80 β HTTP: Web communication.
- Port 443 β HTTPS: Encrypted web communication.
- Port 3306 β MySQL: Database communication.
These are conventional port assignments. However, they do not confirm which application is actually running on a particular port.
Applications can use non-standard ports depending on their configuration. For example, a web application may listen on port 8080 instead of port 80.
Understanding this distinction is important when interpreting port scanning results.
2. What Is TCP Port Scanning?
TCP port scanning is a network discovery technique used to examine how a target system responds to connection attempts on selected TCP ports.
A basic TCP connect scanner attempts to establish a TCP connection with each selected port.
Based on the observed response, ports can generally be classified into different states:
Open
The TCP connection succeeds, indicating that the target endpoint accepts connections.
Closed
The target explicitly refuses the connection, suggesting that no application is listening on that port.
Filtered or inconclusive
A firewall, network restriction, timeout, or other network condition prevents the scanner from determining the port's state reliably.
A timeout does not necessarily mean that a port is closed.
Port scanning is commonly used in authorized network inventories, troubleshooting, and security assessments.
However, finding an open port does not automatically mean that a vulnerability exists. Additional investigation is necessary to understand the service and evaluate its security.
3. Why Use Python to Build a Port Scanner?
Python is a useful programming language for learning network security because it provides built-in modules for networking, concurrency, and data handling.
This project uses several Python capabilities.
Socket Programming
Python's socket module provides an interface for creating network connections and communicating through TCP and UDP.
It is an important component of a basic TCP port scanner because it allows the program to attempt connections to selected ports.
Multithreading
Python's concurrent.futures module provides ThreadPoolExecutor, which can execute multiple tasks concurrently.
This is useful for port scanning because connection attempts may spend time waiting for responses.
Command-Line Argument Parsing
Python's argparse module helps create command-line interfaces and process user-supplied arguments.
It allows users to specify a target and port range when running the scanner.
CSV File Handling
Python's csv module provides functionality for writing structured data to CSV files.
This makes it easier to store and review scan results.
Combining these capabilities provides a practical introduction to network programming, concurrency, command-line tools, and basic cybersecurity automation.
4. Project Overview
The main objective of this project was to develop a simple TCP port scanning utility using Python.
The scanner provides the following features:
- Scan a target IP address or hostname.
- Examine a custom range of TCP ports.
- Detect open ports.
- Display common service names.
- Perform multithreaded scanning.
- Accept command-line arguments.
- Export scan results to a CSV file.
- Display a scan summary, including execution time.
The tool is designed as a beginner-friendly project for understanding TCP connection attempts and basic network discovery.
5. Project Architecture
The project uses a modular structure to separate different responsibilities.
Instead of placing everything inside one Python file, the implementation is organized into separate modules.
The project structure is:
python-port-scanner/
β
βββ scanner.py # Main scanning program
βββ banner.py # Project banner
βββ services.py # Common TCP service names
βββ requirements.txt # Project dependencies
βββ README.md # Project documentation
βββ docs/ # Documentation and screenshots
βββ results/ # Scan results
βββ .gitignorepython-port-scanner/
β
βββ scanner.py # Main scanning program
βββ banner.py # Project banner
βββ services.py # Common TCP service names
βββ requirements.txt # Project dependencies
βββ README.md # Project documentation
βββ docs/ # Documentation and screenshots
βββ results/ # Scan results
βββ .gitignorescanner.py
This is the main program responsible for running the port scanner.
It handles the target and port-range arguments and coordinates the scanning process.
banner.py
This module is responsible for displaying the project's banner when the tool is executed.
services.py
This module handles common TCP service names associated with port numbers.
It helps provide additional context when reviewing scan results.
requirements.txt
This file lists the Python dependencies required by the project.
docs/
This directory stores project documentation and screenshots.
results/
This directory is used to store generated scan results.
Separating functionality into modules makes the project easier to understand, maintain, and extend.
6. Installing the Python TCP Port Scanner
To use the project, you need Python 3 installed on your computer.
Step 1: Clone the repository
Open your terminal and run:
git clone https://github.com/Sreedev-Sreekumar/python-port-scanner.gitgit clone https://github.com/Sreedev-Sreekumar/python-port-scanner.gitStep 2: Navigate to the project directory
cd python-port-scannercd python-port-scannerStep 3: Install dependencies
Install the dependencies listed in the project's requirements file:
pip install -r requirements.txtpip install -r requirements.txtThe project uses Python's standard networking and concurrency capabilities. Any additional dependencies should be listed in requirements.txt.
7. Running the Scanner
The scanner accepts a target and a custom range of TCP ports through its command-line interface.
The general command format is:
python scanner.py <target> <start_port> <end_port>python scanner.py <target> <start_port> <end_port>Here is what each argument represents:
- target: The hostname or IP address to scan.
- start_port: The first TCP port in the selected range.
- end_port: The last TCP port in the selected range.
Example 1: Scan localhost
To examine ports 1 through 1024 on your own computer, run:
python scanner.py 127.0.0.1 1 1024python scanner.py 127.0.0.1 1 1024Example 2: Scan a smaller port range
To examine ports 440 through 450 on localhost, run:
python scanner.py localhost 440 450python scanner.py localhost 440 450These commands are examples. The actual results depend on which services are listening on the target system and how its network environment is configured.
Important: Only scan systems you own or have explicit permission to assess.
8. Understanding the Scan Output
After executing the scanner, the program displays the discovered open ports and a summary of the scanning process.
An illustrative example of the output is:
==================================================
PORT STATUS SERVICE
==================================================
135 OPEN MSRPC
445 OPEN Microsoft-DS
==================================================
SCAN SUMMARY
==================================================
Target : 127.0.0.1
Resolved IP : 127.0.0.1
Ports Scanned : 1024
Open Ports Found : 2
Time Taken : 1.34 seconds
====================================================================================================
PORT STATUS SERVICE
==================================================
135 OPEN MSRPC
445 OPEN Microsoft-DS
==================================================
SCAN SUMMARY
==================================================
Target : 127.0.0.1
Resolved IP : 127.0.0.1
Ports Scanned : 1024
Open Ports Found : 2
Time Taken : 1.34 seconds
==================================================The output provides several useful details.
Target
Displays the hostname or IP address supplied by the user.
Resolved IP
Displays the IPv4 address associated with the target.
Ports Scanned
Indicates how many ports were examined.
Open Ports Found
Shows the number of ports identified as open.
Time Taken
Displays the time taken to complete the scan.
The service column provides a conventional service name associated with the port number.
The output above is illustrative and should not be interpreted as a scan performed on every computer. Actual results and execution time will vary.
9. Multithreading and Scanning Performance
Scanning ports sequentially means that the program waits for one connection attempt to finish before moving to the next.
This can become inefficient when connection attempts take time to complete, particularly when ports do not respond immediately.
Multithreading helps address this limitation by allowing multiple connection checks to execute concurrently.
Python provides ThreadPoolExecutor through its concurrent.futures module.
Using a thread pool allows the scanner to manage multiple scanning tasks without manually creating and managing every thread.
However, increasing the number of concurrent workers does not automatically improve performance.
Scanning efficiency depends on several factors:
- Network latency.
- Connection timeout settings.
- Available system resources.
- Number of ports being examined.
- Target system and network conditions.
A reasonable concurrency limit helps balance performance and resource usage.
10. Exporting Scan Results to CSV
In addition to displaying scan results in the terminal, the project supports exporting results to a CSV file.
CSV stands for Comma-Separated Values. It is a simple format used to store structured information in rows and columns.
The scanner saves its results to:
results/scan_results.csvresults/scan_results.csvAn illustrative CSV report could look like this:
Port,Status,Service 135,OPEN,MSRPC 445,OPEN,Microsoft-DS
These are example entries, not verified results from an actual scan.
CSV reporting is useful because the generated data can be opened using spreadsheet applications or processed using Python.
It also provides a convenient way to document and compare results from authorized network assessments.
11. Limitations of a Basic TCP Port Scanner
Although this project provides useful functionality for learning network discovery, it has limitations.
Open ports do not automatically indicate vulnerabilities.
An open port only indicates that the target accepts a TCP connection. Additional investigation is necessary to determine whether the associated service has security weaknesses.
Service names are not verified identities.
A port number can be associated with a conventional service name, but this does not prove which application is actually running.
Network conditions can affect scan results.
Firewalls, packet loss, routing problems, and timeouts can affect the responses received by the scanner.
Scanning speed has trade-offs.
Aggressive concurrency can increase network traffic and system resource usage.
Limited scanning scope.
This project focuses on TCP port scanning. It does not provide comprehensive UDP scanning, operating system detection, vulnerability identification, or advanced service fingerprinting.
Understanding these limitations is important when interpreting results and deciding whether additional security testing is necessary.
12. Responsible and Ethical Port Scanning
Port scanning is a legitimate technique in network administration and cybersecurity when performed with appropriate authorization.
However, scanning systems without permission can violate organizational policies or applicable laws.
Before conducting a scan:
- Confirm that the target is yours or that you have explicit permission to test it.
- Respect the agreed testing scope.
- Use reasonable scanning settings.
- Avoid unnecessary disruption to production services.
- Store and share scan results responsibly.
For beginners, localhost and intentionally provided practice environments are good starting points.
Responsible testing is an important part of professional cybersecurity practice.
13. Future Improvements
This project provides a foundation for exploring more advanced network security capabilities.
Some possible future improvements include:
UDP Port Scanning
Extend the scanner to examine UDP ports in addition to TCP ports.
Banner Grabbing
Introduce functionality to collect service banners where appropriate, helping identify information about responding services.
Service Version Detection
Explore methods for identifying the software and versions associated with open ports.
Operating System Detection
Investigate techniques for estimating the target operating system.
Progress Bar
Add a progress indicator to provide better feedback during longer scans.
JSON Export
Support JSON output alongside CSV reporting.
Graphical User Interface
Develop a GUI to make the scanner easier to operate without using command-line arguments.
These improvements could turn the basic scanner into a more comprehensive network discovery tool.
Conclusion
Building a Python TCP port scanner was a practical way to explore networking and cybersecurity fundamentals.
Through this project, I worked with socket programming, TCP port scanning, Python modules, multithreading, command-line arguments, service identification, and CSV file handling.
More importantly, the project helped demonstrate how networking concepts can be translated into a working cybersecurity utility.
A port scanner is only one part of network reconnaissance, and its results must be interpreted carefully. Identifying an open port does not automatically establish that a system is vulnerable.
For anyone beginning their journey in network security, building a scanner from scratch is a valuable exercise in understanding how network services communicate and how basic security tools operate.
I'm continuing to learn, build, and explore practical cybersecurity projects as I develop my skills in network security and offensive security.
References and Further Reading
1.Python Software Foundation β Socket Programming
https://docs.python.org/3/library/socket.html
2.Python Software Foundation β Concurrent Execution
https://docs.python.org/3/library/concurrent.futures.html
3.Python Software Foundation β Argparse
https://docs.python.org/3/library/argparse.html
4.Python Software Foundation β CSV File Reading and Writing
https://docs.python.org/3/library/csv.html
5.IANA β Service Name and Transport Protocol Port Number Registry
https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
6.Nmap Project β Official Network Scanning Documentation
https://nmap.org/book/man.html
Disclaimer: This project and article are intended for educational purposes. Scan only systems you own or have explicit permission to assess.
Project Repository: https://github.com/Sreedev-Sreekumar/python-port-scanner
Let's Connect
π LinkedIn β Sreedev Sreekumar
π GitHub β Sreedev Sreekumar
π Python TCP Port Scanner β Project Repository