Simple Port Scanner: Fast Network Reconnaissance with Python
Network reconnaissance is the first step in securing any infrastructure. Understanding which ports are open on your servers helps you identify potential vulnerabilities before malicious actors do. While professional tools like Nmap are excellent, building your own lightweight port scanner in Python is a fantastic way to understand the underlying mechanics of network protocols.
Here is how to build a fast, functional port scanner using Python’s built-in socket library. Understanding the Core Logic
At its core, a port scanner attempts to establish a network connection with a specific IP address on a specific port. If the connection succeeds, the port is “open.” If it fails or times out, the port is likely “closed” or blocked by a firewall.
In Python, we achieve this using the socket module, which handles low-level networking interfaces. The Basic Single-Threaded Script
The following script iterates through a specified range of ports and attempts to connect to each one.
import socket import sys from datetime import datetime # Define the target (use localhost or a safe testing IP) target_host = “127.0.0.1” print(“-“50) print(f”Scanning target: {target_host}“) print(f”Time started: {str(datetime.now())}“) print(”-” * 50) try: # Scan ports from 1 to 1024 for port in range(1, 1025): # Create a socket object # AF_INET specifies IPv4, SOCK_STREAM specifies TCP s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Set a timeout so the script doesn’t hang indefinitely s.settimeout(0.5) # Attempt to connect to the target IP and port result = s.connect_ex((target_host, port)) # connect_ex returns 0 if the connection was successful if result == 0: print(f”Port {port}: OPEN”) # Close the socket connection s.close() except KeyboardInterrupt: print(” Exiting script.“) sys.exit() except socket.gaierror: print(” Hostname Could Not Be Resolved.“) sys.exit() except socket.error: print(” Server not responding.“) sys.exit() Use code with caution. Key Code Explanations
socket.connect_ex(): Unlike connect(), which raises an exception on failure, connect_ex() returns an error code. It returns 0 if the operation succeeded (port open) and an error number (like 111 for connection refused) if it failed. This makes the code cleaner and faster.
s.settimeout(0.5): This drops the wait time to half a second per port. Without a timeout, your script might wait up to two minutes for a response from a single closed port. Speeding It Up with Threading
The single-threaded approach works, but scanning 1,024 ports sequentially at 0.5 seconds per port takes over 8 minutes. We can drastically speed this up by using the threading module to scan multiple ports simultaneously.
import socket import threading from queue import Queue target = “127.0.0.1” queue = Queue() open_ports = [] # Populate the queue with ports to scan for port in range(1, 1025): queue.put(port) def scan_port(): while not queue.empty(): port = queue.get() try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(0.5) result = s.connect_ex((target, port)) if result == 0: print(f”Port {port} is open”) open_ports.append(port) s.close() except: pass finally: queue.task_done() # Launch 100 threads to process the queue concurrently thread_list = [] for _ in range(100): thread = threading.Thread(target=scan_port) thread_list.append(thread) thread.start() # Wait for all threads to finish for thread in thread_list: thread.join() print(f”Scan complete. Open ports: {sorted(open_ports)}“) Use code with caution.
By introducing 100 concurrent threads, the entire scan of 1,024 ports finishes in just a few seconds rather than minutes. Ethics and Legalities
Port scanning generates noticeable network traffic. Unauthorized scanning of networks you do not own or have explicit permission to test can be interpreted as a malicious act or a precursor to a cyberattack.
Always restrict your testing to 127.0.0.1 (your local machine) or environments specifically built for penetration testing practice, such as Hack The Box or TryHackMe. Next Steps
This script performs a basic TCP Connect scan. To take your reconnaissance tool to the next level, you can explore adding banner grabbing (reading the text data returned by a port to identify the software version running) or upgrading the script to use asyncio for modern asynchronous network programming.
If you would like to expand this tool, let me know if you want to add banner grabbing to detect services, rewrite it using modern asyncio, or add a command-line interface (CLI) for custom inputs. Saved time Comprehensive Inappropriate Not working
A copy of this chat, including the images and video, will be included with your feedback A copy of this chat will be included with your feedback
Your feedback will include a copy of this chat and the image from your search
Your feedback will include a copy of this chat, any links you shared, and the image from your search.
Thanks for letting us know
Google may use account and system data to understand your feedback and improve our services, subject to our Privacy Policy and Terms of Service. For legal issues, make a legal removal request.