Search code examples
pythonscapytraceroute

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). 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). I think that the sr1 function waiting for answer but it never gets it. 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. 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()

Solution

  • Use 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...