Python 类 和界限

Python Classes and bounds

我正在努力思考我为 Scapy 找到的一段代码。

from scapy.utils import RawPcapReader
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP, TCP
        for pkt_data, pkt_metadata in RawPcapReader(file_name):

        ether_pkt = Ether(pkt_data)          
        if 'type' not in ether_pkt.fields:
            # LLC frames will have 'len' instead of 'type'.
            # We disregard those
            continue

        if ether_pkt.type != 0x0800:
            # disregard non-IPv4 packets
            continue

        ip_pkt = ether_pkt[IP]

让我感到困惑的部分是我的对象ether_pkt被分配给class以太币 但是 ip_pkt = ether_pkt[IP]

这里发生了什么?

python 的一件有趣的事情是你可以 bind all operators to do custom things。例如,您可以创建一个对象,其中 + 运算符执行完全不同的操作。

在 scapy 中,括号运算符被实现为表示从数据包中“获取下一层”。在这里,您通过指定第一层来剖析数据包:以太网。这将剖析所有子层,其中包括 IP。

pkt = Ether()/IP()
pkt[IP] # Only the IP layer
d = bytes(pkt)  # The full packet as bytes
Ether(d)[IP]  # Dissect the packet, get the IP layer

有关 https://scapy.readthedocs.io/en/latest/usage.html

的更多信息