Traceroute is used to track the internet nodes your data packet travels through on it's way to it's destination. A few days ago I was asked how traceroute works. Even though I use it quite often I was not able to answer. So I did some studying and here are the results.
When you give the command
traceroute www.example.com
traceroute starts sending packets to the server hosting www.example.com. For the first packet it will set the TTL (Time To Live) value to 1, and then increase it by one for the next packet. It will keep doing this until a packet finally reach the destination.
Every packet travelling in the Internet has a TTL value. This value is decreased every time a router forwards a packet in a network. It prevents the packets from getting into an infinite loop and congesting the network. When the TTL value is reduced to zero the packet is discarded.
Traceroute is able to give a detailed hop-count and some information about the nodes, because when a router discards a TTL=0 packet, it will send ICMP "time exceeded in transit" message to the sender. Packets are sent, by default, using UDP protocol and they are destined to a random port in the normally unused port range between 33434 - 33534. When the TTL value has increased enough and the packet finally reaches its destination, the destination server will reply with ICMP "UDP port unreachable" message. This is completely different compared to the "time exceeded in transit" messages so traceroute will know a packet has reached the destination.
Below is a screen capture of UDP port unreachable messages my test machine received from a server on the same network.
This data was captured with tcpdump. You can test your traceroute and inspect the sent and received packets with the following command in linux:
sudo tcpdump -ni wlan0 -vvv 'udp or icmp'
- "-n" flag tells tcpdump not to convert addresses into names
- "-i" flag tells tcpdump which interface to use. I used wlan0 because I connect to the network using WLAN
- "-vvv" flag tells tcpdump to be very verbose
- 'udp or icmp' tells tcpdump to capture only UDP and ICMP traffic. Note that if you change the traceroute default protocol you have to change this command too.
- As a default the packets are sent as UDP, but the replys always come as ICMP.
When you inspect the traffic sent by traceroute, you will notice that it is actually sending three packets per every TTL value. This is because it will measure the round trip time to the node as an average of three packets to be more precise.
Sometimes traceroute can't get a reply from a router. This is because some of the routers are set not to reply to UDP/ICMP requests. You can change the protocol used by traceroute from UDP to TCP with "-T" flag. I have been able to get much more accurate results using TCP. If that doesn't work, you can also try "-I" flag for ICMP.