首页 > 解决方案 > Python 类和边界

问题描述

试图围绕我为 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被分配给Ether类 ,但是随着ip_pkt = ether_pkt[IP]

这里发生了什么?

标签: python-3.xpython-class

解决方案


python 的一件有趣的事情是你可以绑定所有的操作符来做自定义的事情。例如,您可以创建一个对象,其中+操作员执行完全不同的操作。

在 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的更多信息


推荐阅读