Python 100 project #32: Simple Traceroute

This is a simple traceroute script in python3. I refer this post  and the most of the code is as-is. In the later project, I will add tcptraceroute in this script.

 

Output Example:

$ python3 ntwk_basetools.py 
1: 192.168.1.1
2: 100.64.x.x
3: 172.17.2.76
4: 172.16.17.192
5: 172.16.24.26
6: 172.16.25.234
7: 172.16.24.82
8: 77.67.98.205
9: 89.149.140.253
10: 77.67.98.54
11: 129.250.4.140
12: 129.250.2.18
13: 129.250.4.13
14: 129.250.6.30
15: 129.250.3.61
16: 129.250.2.40
17: 117.103.176.138
18: 124.83.228.197

 

Here is the code:

from scapy.all import *

TIMEOUT = 60

def udptraceroute(hostname):

    result = []
    for i in range(1, 28):
        pkt = IP(dst=hostname, ttl=i) / UDP(dport=33434)
        reply = sr1(pkt, verbose=0, timeout=TIMEOUT)
        if reply is None:
            # No reply =(
            break
        else:
            result.append(reply)
            if reply.type == 3:
                # We've reached our destination
                # print "Done!", reply.src
                break
            else:
                # We're in the middle somewhere
                # print "%d hops away: " % i , reply.src

    return result

if __name__ == "__main__":
    result = udptraceroute("www.yahoo.co.jp")

    for id, reply in enumerate(result, start=1):
        print(f"{id}: {reply[0].src}")