Introduction
Cybersecurity is an increasingly important field in today’s digital world. Organizations and individuals are constantly seeking new methods and tools to protect their networks. In this context, network analysis and port scanning play a critical role in identifying vulnerabilities and preventing potential threats. Port scanning is a common technique used to determine which services are running on a target system. This process is frequently employed by network administrators and cybersecurity professionals to evaluate the security of systems. Scapy is a Python-based network toolkit that allows users to create, send, receive, and analyze network packets. The flexibility and power offered by Scapy make it an ideal tool for network analysis. In this article, we will learn how to create a simple port scanner using Scapy. For more information, you can refer to the book “Mastering Scapy: A Comprehensive Guide to Network Analysis”.
Learning Objectives
By the end of this article, you will have knowledge in the following areas:
- Network Fundamentals: Understanding the structure of fundamental network protocols such as TCP/IP, UDP, and ICMP.
- Network Scanning and Enumeration: Identifying open ports, services using Scapy.
- Traffic Analysis and Monitoring: Learning real-time packet capture, logging.
- Attack Detection and Simulation: Developing skills to simulate various network attacks.
Port Scanning with Scapy
Port scanning is a process used to determine which ports are open on a target system. Open ports help identify the services running on the system. This information is critical for detecting potential vulnerabilities and implementing security measures. We will create a simple port scanner using Scapy. Below is the Python code that accomplishes this task.
Mastering Scapy: A Comprehensive Guide to Network Analysis
Mastering Network Analysis with Scapy” is not just about learning a tool; it’s about unlocking a deeper understanding of the digital world that surrounds us
-5% $20 on buymeacoffeeLet’s Write Our Code
Below is a simple port scanner code using Scapy. We will examine this code step by step to understand the function of each section.
1. Importing Libraries
- argparse: Used for managing command-line arguments, allowing users to input the target IP address and ports to be scanned.
- scapy.all: Imports all components of the Scapy library, necessary for creating and sending network packets using IP and TCP protocols.
- colorama: Used for coloring terminal output, providing users with more readable output.
The statement init(autoreset=True)
ensures that color settings are automatically reset, so we do not have to manually reset them for each new color usage.
import argparse
from scapy.all import IP, TCP, sr
from colorama import Fore, init
# Colorama initialization
init(autoreset=True)
2. PortScanner Class
- PortScanner Class: This class is designed to perform port scanning operations.
__init__
Method: This is the constructor method of the class. It takestarget_ip
andports
parameters and stores them as class attributes.target_ip
represents the IP address of the target to be scanned;ports
represents the list of ports to be scanned.
class PortScanner:
def __init__(self, target_ip, ports):
self.target_ip = target_ip
self.ports = ports
3. Processing Port Input
- parse_ports Method: This method processes the port input received from the user. This input can include single ports or ranges (e.g.,
80-100
). - Parsing Port Input: The input is split into comma-separated parts.
- If a part contains a
-
, it indicates a range. If a range is specified, all ports within that range are added to a set. - Single ports are added directly to the set.
- As a result, all ports are returned as a sorted list.
def parse_ports(self, port_input):
"""Parse the input for ports which can be a single port or a range."""
ports = set()
for part in port_input.split(','):
if '-' in part:
start_port, end_port = part.split('-')
ports.update(range(int(start_port), int(end_port) + 1))
else:
ports.add(int(part))
return sorted(ports)
4. Scanning Process
- scan Method: This method scans the specified ports on the target IP.
- First, an informational message is printed for the target IP.
- A SYN packet is sent for each port (
TCP(dport=port, flags="S")
). This packet is used to check whether a specific port is open. - When a response is received (response), each response is checked:
- If the response is SYN-ACK (flag value 18), it means that this port is open and it is printed in green.
- If the response is RST (flag value 20), it means that this port is closed and it is printed in red.
- If no response can be received or if it is filtered, a blue message is printed.
def scan(self):
"""Scan the specified ports on the target IP.
https://www.wireshark.org/docs/wsug_html_chunked/ChAdvTCPAnalysis.html
"""
print(Fore.YELLOW + f"Scanning {self.target_ip} for open ports...")
for port in self.ports:
response = sr(IP(dst=self.target_ip)/TCP(dport=port, flags="S"), timeout=1, verbose=0)[0]
if response:
for sent, received in response:
if received.haslayer(TCP) and received[TCP].flags == 18: # SYN-ACK
print(Fore.GREEN + f"Port {port} is open")
elif received.haslayer(TCP) and received[TCP].flags == 20: # RST
print(Fore.RED + f"Port {port} is closed")
else:
print(Fore.BLUE + f"Port {port} is filtered or no response")
5. Main Function
- main Function: This serves as the entry point of the program. It processes command-line arguments.
argparse.ArgumentParser
: Creates a new argument parser.--target
or-t
: A required argument for the target IP address or hostname.--port
or-p
: An optional argument for specifying the list of ports to scan.
def main():
parser = argparse.ArgumentParser(description='Simple TCP Port Scanner using Scapy')
parser.add_argument('--target', '-t', type=str, required=True, help='Target IP address or hostname')
parser.add_argument('--port', '-p', type=str, help='List of ports to scan (e.g., 22,80-100), default scans first 1000 ports')
args = parser.parse_args()
6. Starting the Scanner
- If there are any provided port details (
args.port
), this information will be processed to create aPortScanner
instance. - If no port has been specified by the user, it defaults to scanning the first 1000 ports (
range(1, 1001)
). - Finally, scanning begins with
scanner.scan()
.
if args.port:
scanner = PortScanner(args.target, PortScanner(args.target, []).parse_ports(args.port))
else:
default_ports = range(1, 1001)
scanner = PortScanner(args.target, default_ports)
scanner.scan()
7. Running the Program
- This line ensures that when the script is run directly, it calls the
main()
function so that when executed, it triggers the main function.
if __name__ == "__main__":
main()

Conclusion
With the above code snippet, we have created a simple port scanner. This tool allows us to detect open ports on a specific IP address. Identifying open ports helps understand which services are running on systems while also enabling potential security vulnerabilities to be detected. The flexibility of Scapy allows for more complex analyses and attack simulations as well. For example; you can conduct deeper analyses targeting specific protocols or simulate various types of attacks.
Mastering Python for Ethical Hacking: A Comprehensive Guide to Building 50 Hacking Tools
Let’s embark on this journey together, where you will learn to use Python not just as a programming language, but as a powerful weapon in the fight against cyber threats
-5% $25 on buymeacoffeeThis article has not only guided you in creating a basic network scanner using Scapy but also taken steps towards enhancing your competence in cybersecurity. I recommend checking out “Mastering Scapy” for further information. These resources will help you improve your skills in network analysis and develop your cybersecurity capabilities. Remember that cybersecurity is an ever-evolving field; staying updated is crucial!