但是sniff并没有停止
时间: 2023-09-16 14:11:07 浏览: 126
我注意到您在代码中使用了 `stop_filter` 参数来停止嗅探。通常情况下,当 `stop_filter` 函数返回 `True` 时,它应该停止嗅探。但是有时可能会出现一些问题,导致 `sniff` 函数无法自行停止。在这种情况下,您可以使用一个标志变量来手动停止嗅探。
下面是一个修改过的示例代码,使用全局变量 `stop_sniffing` 来停止嗅探:
```python
import threading
from scapy.all import *
stop_sniffing = False
def packet_callback(packet, port):
# 处理收到的数据包
...
def receive_packets(port, timeout):
global stop_sniffing
start_time = time.time()
while not stop_sniffing and time.time() - start_time < timeout:
sniff(prn=lambda packet: packet_callback(packet, port), filter="tcp port {}".format(port), count=1)
print("Stopped sniffing")
def stop_sniffing_process():
global stop_sniffing
stop_sniffing = True
# 启动嗅探线程
src_port = 80
timeout = 10
receive_thread = threading.Thread(target=receive_packets, args=(src_port, timeout))
receive_thread.start()
# 在另一个进程中停止嗅探
stop_sniffing_process()
# 等待嗅探线程结束
receive_thread.join()
```
在这个示例中,`receive_packets` 函数使用一个循环来嗅探数据包,直到 `stop_sniffing` 变量被设置为 `True`,或者超时时间到达。当 `stop_sniffing` 变量被设置为 `True` 时,`receive_packets` 函数会停止嗅探,并打印一条消息。 `stop_sniffing_process` 函数通过设置 `stop_sniffing` 变量来停止嗅探。