这段代码无法正常停止,请修改
时间: 2024-03-20 20:38:49 浏览: 19
如果你运行这段代码发现无法正常停止线程,可以尝试在 `sniff` 方法中添加 `timeout` 参数,设置超时时间,然后在超时时间到达后手动退出线程。以下是修改后的代码:
```python
import threading
from scapy.all import *
class SnifferThread(threading.Thread):
def __init__(self):
super().__init__()
self.stop_flag = False
def run(self):
while not self.stop_flag:
try:
sniff(filter="icmp", prn=lambda x: x.summary(), timeout=1)
except:
pass
def stop(self):
self.stop_flag = True
if __name__ == "__main__":
sniffer_thread = SnifferThread()
sniffer_thread.start()
input("Press Enter to stop...")
sniffer_thread.stop()
sniffer_thread.join()
```
在上面的代码中,将 `sniff` 方法的 `timeout` 参数设置为 `1` 秒,表示每次抓包最多等待 1 秒钟,如果在 1 秒内没有抓到数据包,则会自动返回。在 `run` 方法中,使用 `try-except` 语句捕捉超时异常,如果出现超时,则直接跳过本次循环。这样就可以避免无法正常停止线程的问题了。