8

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.

Jongware
  • 22,200
  • 8
  • 54
  • 100
Quentin
  • 435
  • 2
  • 6
  • 15

1 Answers1

16

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

from scapy.all import raw
raw(packet)

The former is cross-version compatible, but if you are guaranteed to run with Python 3 and support for Python 2 is not needed, you can simply invoke bytes, which doesn't require an ad-hoc import statement (and is actually how scapy.compat.raw is implemented behind the scenes):

bytes(packet)

You can print the raw bytes of the packet 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.

Yoel
  • 9,144
  • 7
  • 42
  • 57
  • This is outdated / the function doesn't exist anymore. In Python 3 it seems you can just call a `bytes(packet)`, no imports needed. – mozzbozz Oct 04 '21 at 17:43
  • Thanks for you comment. I've edited my answer to reflect the option to directly invoke `bytes(packet)` in _Python 3_. However, I do believe that `scapy.compat.raw` still [exists](https://github.com/secdev/scapy/blob/master/scapy/compat.py#L264) and has the advantage of cross-version compatibility. – Yoel Oct 05 '21 at 20:17