9

In Scapy (or even just Python, for that sake), how do I get the size in bytes of a given packet? I'm tempted to use the function len but I'm not sure what exactly it returns in the case of packets.

>>> len(IP(dst="www.google.com"))
20

>>> len(IP(dst="www.google.com")/TCP(dport=80))
40
Ricky Robinson
  • 21,798
  • 42
  • 129
  • 185
  • Is len giving packet size, and if there are 1000 packets generated from the tcpdumpfile. Does the length of each of these packets summed up provide you with actual data transfer size? Do advise – ramdaz Jun 04 '12 at 09:04

3 Answers3

10
>>> len(IP(dst="www.google.com"))
20

There are 20 bytes in a minimal IP header.

>>> len(IP(dst="www.google.com")/TCP(dport=80))
40

There are another 20 bytes in a minimal TCP header (20+20==40).

So it seems that len is returning the packet length.

MattH
  • 37,273
  • 11
  • 82
  • 84
2

What I have been observing is that Len(packet[Layer]) will actually perform the action of the LenField type. It will return the number of bytes in the packet, starting with the specified layer, all the way to the end of the packet. So while this method will work for determining the overall packet size, just beware that it will not work to determine the length of an individual layer.

2

Here is how I grab the packet size/length when sniffing packets with scapy.

pkt.sprintf("%IP.len%")

Full example:

from scapy.all import *

# callback function - called for every packet
def traffic_monitor_callbak(pkt):
    if IP in pkt:
        print pkt.sprintf("%IP.len%")

# capture traffic for 10 seconds
sniff(iface="eth1", prn=traffic_monitor_callbak, store=0, timeout=10)

I've only used scapy for sniffing packets, so I'm not sure if the above makes sense when using scapy for other things like creating packets.

Banjer
  • 8,118
  • 5
  • 46
  • 61
  • 1
    why don't you just do `len(p)` for every packet `p`? – Ricky Robinson Jan 13 '14 at 17:46
  • 1
    Both seem to work for me. I'm just showing that the actual packet length can be grabbed from the packet itself. The `pkt.sprintf` function in scapy is pretty useful in grabbing various header fields, so just showing its use here as well. – Banjer Jan 13 '14 at 18:25