How to extract Raw of TCP packet using Scapy

Kuaaaly picture Kuaaaly · Nov 27, 2014 · Viewed 20.3k times · Source

I use the sniff function of scapy module. My filter and prn function are doing a great job. But now, I would like to extract the Raw of the TCP packet and handle it using hexadecimal or binary format.

Here is the documentation of Packet Class in scapy.

How can I do that ?

I tried print packet[Raw] but it seems to be converted as ASCII or something like that. I want to keep it in hexadecimal or binary.

Answer

Yoel picture Yoel · Nov 27, 2014

You can get the raw bytes of the packet using scapy.compat.raw1:

from scapy.all import raw
raw(packet)

You can print them in a readable format using scapy.compat.bytes_hex2:

from scapy.all import bytes_hex
print(bytes_hex(packet))

1 scapy.compat.raw's implementation can be found here.
2 scapy.compat.bytes_hex's implementation can be found here.