[英]How to handle request timed out in python - traceroute script using scapy
I'm trying to code traceroute program using Python and Scapy (with ICMP). 我正在尝试使用Python和Scapy(带有ICMP)编写traceroute程序的代码。 I have a problem that sometimes I don't get a reply from the destination, and my program is just stuck waiting for it.
我有一个问题,有时我没有收到目的地的答复,而我的程序只是在等待它。 (When using traceroute on cmd this is the equivalent of the "Request timed out" situation).
(在cmd上使用traceroute时,这相当于“请求超时”情况)。 I think that the sr1 function waiting for answer but it never gets it.
我认为sr1函数正在等待答案,但从未得到它。 How can I fix it?
我该如何解决?
I'm also not sure I handled the case that I got to the destination, I checked if the type is equal to 3 but I'm not sure it's right. 我也不确定我是否处理了到达目的地的情况,我检查了类型是否等于3,但不确定是否正确。 I'll be happy to get answer about that too.
我也很乐意得到答案。
import sys
i, o, e = sys.stdin, sys.stdout, sys.stderr
from scapy.all import *
sys.stdin, sys.stdout, sys.stderr = i, o, e
def main():
hostname = input("Enter the destination")
done = False
distance = 1
while not done:
tracert_packet = IP(dst=hostname, ttl=distance)/ICMP()
# Send the packet and get a reply
tracert_resopnse = sr1(tracert_packet, verbose=0)/ICMP()
if tracert_resopnse.type == 3:
# We've reached our destination
print("Done!" + tracert_resopnse[IP].src)
done = True
else:
# We haven't got to the destination yet
print(str(distance) +" hops away: "+ str(tracert_resopnse.src))
distance += 1
if __name__ == '__main__':
main()
Use sr1(tracert_packet, verbose=0, timeout=TIMEOUT_VAL)
. 使用
sr1(tracert_packet, verbose=0, timeout=TIMEOUT_VAL)
。 If there is no answer the return value will be None
,so check before you concatenate with ICMP
... 如果没有答案,则返回值为
None
,因此请在与ICMP
连接之前检查...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.