如何验证Scapy中的数据包是否具有TCP层

12

我想知道如何验证我从Scapy的sr1()函数接收到的数据包是否包含TCP层,以便对TCP标志进行一些处理。

2个回答

13

你有两种选择,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.'

非常感谢RyPeck的回答,问题在于我要检查的数据包是Scapy中sr1()命令的结果,所以这些选项对我没有用。不幸的是,我收到了这个错误消息:AttributeError: 'NoneType' object has no attribute 'haslayer'。 - farfalla
听起来好像是因为你实际上没有从sr1收到数据包。 - RyPeck

-1
接受的答案可以在意想不到的地方匹配协议。在健壮的代码中,您应该使用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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接