如何使用 scapy 计算捕获的数据包大小

How to Calculate Captured Packet(s) Size using scapy

最近我开始使用 Scapy 编写代码。基于以下示例:

Scapy Sniffing with Custom Actions

我捕获多播 UDP 数据报,但除了每秒捕获的数据包数量外,我还想存储每秒捕获的数据包的大小(以字节为单位)(我将结果乘以 8,然后我会有比特率)。 问题是 capturedPacketsSize 似乎未定义,但我在 def custom_action() 之前定义了它。

我试图在不同的地方定义 capturedPacketsSize 例如在 while 1 循环中嗅探之前。同样的结果。

from collections import Counter
from scapy.all import sniff

packet_counts = Counter()

capturedPacketsSize = 0

## Define our Custom Action function
def custom_action(packet):
    # Create tuple of Src/Dst in sorted order
    capturedPacketsSize += len(packet)     #here occurs error
    key = tuple(sorted([packet[0][1].src, packet[0][1].dst]))
    packet_counts.update([key])
    #return "Packet #{0}: {1} ==> {2}".format(sum(packet_counts.values()), packet[0][1].src, packet[0][1].dst)



print("_____.:|Entering infinite while loop|:._____")

while 1:
    print("Analysing Multicast packets")
    pkt = sniff(iface="eno4", filter="udp", prn=custom_action, timeout=1)
    print("\n".join("{0} <--> {1} :{2}".format(key[0], key[1], count) for key, count in packet_counts.items()))
    packet_counts.clear()
    print("Byterate for this moment is equal to: {0} Bytes per second".format(capturedPacketsSize))

函数内的变量名使用global关键字-

def custom_action(packet):
    global capturedPacketsSize
    global packet_counts
    # Create tuple of Src/Dst in sorted order
    capturedPacketsSize += len(packet)     #here occurs error
    key = tuple(sorted([packet[0][1].src, packet[0][1].dst]))
    packet_counts.update([key])

您可以阅读有关此关键字的更多信息here