python-3.x - 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 的一件有趣的事情是你可以绑定所有的操作符来做自定义的事情。例如,您可以创建一个对象,其中+
操作员执行完全不同的操作。
在 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
推荐阅读
- pygame - 哪些 pygame 模块具有 init 属性?我想手动初始化模块而不是使用 pygame.init()
- mysql - MySql 日期时间格式更改
- python - Command errored out with exit status 1: Building wheel for pysph (setup.py) ... error
- ffmpeg - 使用 ffmpeg 将 heif 文件转换为 png/jpg
- elasticsearch - Kibana painless script to count the json list size
- javascript - Palindrome Index Hackerrank with JavaScript
- jobs - 测试数据生成的作业可以在 HCL OneTest Data 中保留多长时间?用户可以为作业配置此时间段吗?
- google-apps-script - 无法在谷歌脚本中连接
- php - 如果数据存在,PHP隐藏一个按钮
- macos - latexindent:自 macOS 11 Big Sur 起安装 File::HomeDir、Mac::SystemDirectory 时出现问题