How to Perform IP Address Spoofing in Python

Master IP spoofing with Python: Dive into crafting fake IP addresses to test network security. Utilize Scapy and Faker in a hands-on tutorial to send spoofed ICMP packets, complete with practical examples and step-by-step instructions.
  · 7 min read · Updated feb 2024 · Ethical Hacking · Packet Manipulation Using Scapy

Turn your code into any language with our Code Converter. It's the ultimate tool for multi-language programming. Start converting now!

In this tutorial, we will learn how to spoof our  IP addresses in Python. Spoofing IP addresses refers to the act of falsifying or manipulating the source IP address in a network packet to deceive or mislead the recipient about the actual origin of the communication. This technique is often used in malicious activities, such as IP spoofing attacks, Man-in-the-middle attacks, and Denial of Service (DoS) attacks to disguise the sender's true identity and potentially evade security measures.

Disclaimer: This IP spoofing tutorial is for educational purposes only. The content is not intended for any malicious use. I am not responsible for any damages resulting from misusing the information provided. Users are advised to apply this knowledge ethically and within legal boundaries.

Technically, IP spoofing involves altering the source address field in the IP header of a network packet to a falsified or manipulated address. Attackers utilize IP spoofing by inserting a manually manipulated source address in the IP header of a network packet. This enables them to conceal the attack's true origin or bypass security measures, such as packet filters or TCP wrappers, that regulate connections based on the source IP address.

We will implement this by creating a straightforward IP Spoofing program. We will send an ICMP-Echo-Request packet, commonly known as ping, to a remote host utilizing a source IP address that has been deliberately falsified.

In this demonstration, the request will be sent from a Kali Linux machine to a Metasploitable host, showcasing the practical application of the spoofed source IP.  A ping is a network utility tool that sends an Internet Control Message Protocol (ICMP) Echo Request message to a target device and waits for an Echo Reply. It is commonly used to test the reachability of a host on an Internet Protocol (IP) network and measure the round-trip time for messages to travel from the source to the destination and back.

Metasploitable is a deliberately vulnerable virtual machine that security professionals and ethical hackers use for testing and educational purposes. It is pre-configured with various vulnerabilities and weaknesses, allowing users to practice penetration testing and security assessments in a controlled environment. In the password guesser tutorial, we show you how to set it up.

As you may have guessed, we’ll achieve this (IP Spoofing) with the mighty Scapy library, which is a powerful Python-based interactive packet manipulation tool and library that enables network professionals to craft, capture, and analyze network packets for various networking and security purposes.

Also, to simplify the process and eliminate the need to generate fake IP addresses for each demonstration manually, we'll streamline our approach by incorporating the Faker library for automatic IP address generation. This will enhance efficiency and provide a seamless solution for obtaining realistic yet fictional IP addresses for our IP spoofing program. We have a full tutorial about generating other fake entities like names, addresses, and even credit card numbers, similar to some platforms on the dark web. Feel free to check it out here.

So, first things first. We install the necessary packages by running:

$ pip3 install scapy faker colorama

If you're on Windows and have trouble installing Scapy, check out this tutorial.

Colorama is a Python library that simplifies terminal text formatting by allowing the use of ANSI escape codes for colored output on both Windows and Unix-based systems.

Next, open up a Python file, and name it meaningfully, like ip_spoofer.py and follow along. We'll start our program by importing the necessary libraries:

import sys
from scapy.all import sr, IP, ICMP
from faker import Faker
from colorama import Fore, init

import sys: Imports the sys module, providing access to system-specific parameters and functions.

from scapy.all import sr, IP, ICMP: Utilizes Scapy, a packet manipulation library to import functions for sending and receiving packets and IP and ICMP packet construction.

from faker import Faker: Incorporates the Faker library, facilitating the generation of fake data, including IP addresses.

from colorama import Fore, init: Integrates colorama, a Python library to introduce colored text output in the terminal. The Fore module allows setting text foreground color, and init initializes colorama for cross-platform compatibility.

Next, we’ll initialize colorama and Faker, then create a function to generate random IPv4 addresses for us:

# Initialize colorama for colored console output
init()
# Create a Faker object for generating fake data
fake = Faker()

# Function to generate a fake IPv4 address
def generate_fake_ip():
   return fake.ipv4()

Afterwards, we create 2 functions. One is to craft and send our packet, and the other is to display the packet summary. Which is basically the summarized version of the packet’s information:

# Function to craft and send an ICMP packet.
def craft_and_send_packet(source_ip, destination_ip):
   # Craft an ICMP packet with the specified source and destination IP.
   packet = IP(src=source_ip, dst=destination_ip) / ICMP()
   # Send and receive the packet with a timeout.
   answers, _ = sr(packet, verbose=0, timeout=5)
   return answers

# Function to display a summary of the sent and received packets.
def display_packet_summary(sent, received):
   print(f"{Fore.GREEN}[+] Sent Packet: {sent.summary()}\n")
   print(f"{Fore.MAGENTA}[+] Response: {received.summary()}")

Finally, the main body of our program:

# Check if the correct number of command-line arguments is provided
if len(sys.argv) != 2:
   print(f"{Fore.RED}[-] Error! {Fore.GREEN} Please run as: {sys.argv[0]} <dst_ip>")
   sys.exit(1)

# Retrieve the destination IP from the command-line arguments
destination_ip = sys.argv[1]
# Generate a fake source IP
source_ip = generate_fake_ip()

# Craft and send the packet, and receive the response
answers = craft_and_send_packet(source_ip, destination_ip)

# Display the packet summary for each sent and received pair
for sent, received in answers:
   display_packet_summary(sent, received)

This block validates command-line arguments, retrieves a destination IP, generates a fake source IP, crafts, and sends an ICMP packet to the destination. After we receive the response, we display the packet summaries for each sent and received pair, incorporating colorama for colored terminal output.

That’s it! Now, let’s run our code. Remember I said we’ll be making use of Metasploitable for testing. Here is a screenshot of my Metasploitable machine:

This is our destination device. We can see that the destination IP is 192.168.134.129 (inet addr)

Also note that for this program to function effectively, Metasploitable and Kali Linux must be connected since the demonstration involves sending ICMP packets (Pings) from one machine to another. If both systems are installed as virtual machines on the same device (as in our case), you shouldn’t have a problem.

To run the code:

$ python3 ip_spoofer.py 192.168.134.129 

Please replace 192.168.134.129 with the IP address of your own Metasploitable machine (Obviously).

Our result:

Notice that each time we run the program, different IPs get assigned as the source IPs. Also, the target machine (metasploitable) responds to the source IP. So, in a real-world scenario, if we were being malicious, we’d be somewhat untraceable as the target machine sees a source IP that does not belong to us (even if it is us). This is what attackers do when carrying out attacks like DoS and MITM. That’s the beauty of this program.

With that, we’re done! I hope you enjoyed this one!

Check out some of our related network hacking tutorials:

Also, if you want to transition from being a script kiddie to a pro hacker, check out our Ethical Hacking with Python eBook, where you'll build 35+ hacking tools from scratch using Python! 

Happy hacking ♥

Liked what you read? You'll love what you can learn from our AI-powered Code Explainer. Check it out!

View Full Code Build My Python Code
Sharing is caring!



Read Also



Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!