我想知道如何验证我从Scapy的sr1()
函数接收到的数据包是否包含TCP层,以便对TCP标志进行一些处理。
你有两种选择,in
运算符是其中之一。
>>> TCP in pkt
True
>>> if TCP in pkt:
... # Handle TCP Flags
Scapy中的数据包对象还拥有一个名为haslayer()
的函数。
>>> pkt = IP()/TCP()
>>> pkt.haslayer(TCP)
1
>>> pkt2 = IP()/UDP()
>>> pkt2.haslayer(TCP)
0
>>> Packet.haslayer.__doc__
'true if self has a layer that is an instance of cls. Superseded by "cls in self" syntax.'
layers()
方法在协议堆栈的特定位置检查协议。>>> pkt1 = IP()/TCP()
>>> pkt1.layers()
[scapy.layers.inet.IP, scapy.layers.inet.TCP]
>>> pkt1.layers()[1] == TCP
True
>>> pkt2 = IP()/UDP()
>>> pkt2.layers()[1] == TCP
False
RyPeck的回答在封装通信时会给出错误的结果。例如,这里是IP封装在IP中:>>> pkt3 = IP()/IP()/TCP()
>>> pkt3.haslayer(TCP)
True
# We got True although the protocol sent over IP is IP, not TCP.
>>> pkt3.layers()[1] == TCP
False
# Using layers() and the position we want to examine [1] we get the correct result.
sr1
收到数据包。 - RyPeck