简体   繁体   English

在scapy / python中获取数据包大小

[英]get packet size in scapy / python

In Scapy (or even just Python, for that sake), how do I get the size in bytes of a given packet? 在Scapy(或者甚至只是Python,为此),如何获得给定数据包的字节大小? I'm tempted to use the function len but I'm not sure what exactly it returns in the case of packets. 我很想使用函数len但是我不确定在数据包的情况下它究竟返回了什么。

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

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

There are 20 bytes in a minimal IP header. 最小IP头中有20个字节。

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

There are another 20 bytes in a minimal TCP header (20+20==40). 最小TCP头中还有另外20个字节(20 + 20 == 40)。

So it seems that len is returning the packet length. 所以似乎len正在返回数据包长度。

What I have been observing is that Len(packet[Layer]) will actually perform the action of the LenField type. 我一直在观察的是Len(packet [Layer])实际上将执行LenField类型的操作。 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. 因此,虽然此方法可用于确定整体数据包大小,但请注意,确定单个层的长度无效。

Here is how I grab the packet size/length when sniffing packets with scapy. 这是我在使用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. 我只是使用scapy来嗅探数据包,所以我不确定上面使用scapy来创建数据包等其他东西时是否有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM