Traceroute

Traceroute is a network diagnostic utility used for displaying the path taken by a packet to it’s destination. It uses the ICMP protocol to help traverse the path. Each IP packet has an 8 bit TTL field that gets decremented by every router on the path, to prevent the packet from indefinitely circulating the internet (or network). When the TTL value reaches zero an ICMP error ‘Time To Live Exceeded’ is sent back to the sender. We can use this fact to our advantage by discovering all the hops between the source and the destination.

Example:

MyPC --- R1 --- R2 --- R3 --- R4 --- FavoriteServer

In the above example, we can discover R1 by sending an ICMP(echo-request) based IP packet starting with a TTL value of 1 destined to the server. R1 will decrement the TTL, thereby reducing it to zero, which in turn will trigger the ICMP error message TTL exceeded. This error message is sent to the sending machine as an ICMP based IP packet. The source field of this IP packet will have the IP address of R1. We can repeate this exercise by incrementing the TTL value till we no longer get the error message and instead get an ICMP echo-reply message from the destination.

I used Scapy a python based packet crafting library to create a bare bones version of traceroute as per the explanation above.


Python Program 

#traceroute.py

from scapy.all import *
import sys

def main():
    host = sys.argv[1]
   print "Tracroute ", host
    flag = True
    ttl=1
    hops = []
    while flag:
        ans, unans = sr(IP(dst=host,ttl=ttl)/ICMP())
        if ans.res[0][1].type == 0: # checking for  ICMP echo-reply
            flag = False
        else:
            hops.append(ans.res[0][1].src) # storing the src ip from ICMP error message
            ttl +=1
    i = 1
    for hop in hops:
        print i, " " + hop
        i+=1

if __name__ == "__main__":
    main()

Sample output 

apurva$ sudo python2.5 taceroute.py google.com
WARNING: No route found for IPv6 destination :: (no default route?)
Tracroute  google.com
Begin emission:
.Finished to send 1 packets.
..*
Received 4 packets, got 1 answers, remaining 0 packets
.... 

1  192.168.0.1
2  98.234.104.1
3  68.85.190.245
4  68.85.155.74
5  68.86.91.225
6  68.86.85.181
7  68.86.86.122
8  66.208.228.226
9  72.14.232.136
10  64.233.174.19