Follow a packet hop by hop

A packet crosses several links. The IP addresses stay the same, the MAC addresses change on every link, and each router lowers the TTL.

What to build

A program that prints the frame used on every link of a path and says whether the packet arrived.

Requirements

  • Print one line per link: link i: MAC1 > MAC2, SRC to DST, ttl T, where T is the TTL the packet has on that link.
  • A router lowers the TTL by 1 when it receives the packet. If the TTL becomes 0 the router drops it: print dropped at router k (k counts routers from 1) and stop.
  • If the packet reaches the last computer, print delivered.

Input

Line 1: the source IP, the destination IP and the starting TTL. Line 2: the MAC addresses of the nodes along the path, from the source computer through every router to the destination computer (at least 2).

Output

The link lines, then delivered or dropped at router k.

Constraints

1 ≤ TTL ≤ 64; at most 20 nodes on the path.

Example

Input:

10.0.0.5 93.184.216.34 64
m1 m2 m3 m4

Output:

link 1: m1 > m2, 10.0.0.5 to 93.184.216.34, ttl 64
link 2: m2 > m3, 10.0.0.5 to 93.184.216.34, ttl 63
link 3: m3 > m4, 10.0.0.5 to 93.184.216.34, ttl 62
delivered

Why it works

A router only changes the link-layer addresses and the TTL, so the IP addresses stay the same all the way. The TTL falls by one at each router, which is how a looping packet is eventually stopped.

Examples

Example 1 · Input
10.0.0.5 93.184.216.34 64
m1 m2 m3 m4
Expected output
link 1: m1 > m2, 10.0.0.5 to 93.184.216.34, ttl 64
link 2: m2 > m3, 10.0.0.5 to 93.184.216.34, ttl 63
link 3: m3 > m4, 10.0.0.5 to 93.184.216.34, ttl 62
delivered
Example 2 · Input
10.0.0.5 93.184.216.34 2
m1 m2 m3 m4
Expected output
link 1: m1 > m2, 10.0.0.5 to 93.184.216.34, ttl 2
link 2: m2 > m3, 10.0.0.5 to 93.184.216.34, ttl 1
dropped at router 2

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

The IP addresses never change, but each link has its own pair of MAC addresses: link i joins macs[i] and macs[i+1].

Hint 2

A router subtracts 1 from the TTL when it receives the packet, and drops it if the TTL reaches 0.

Hint 3

Only the routers (not the last computer) lower the TTL. Stop the loop as soon as a packet is dropped.

Solution

Show one correct solution (try it yourself first)
src, dst, ttl = input().split()
ttl = int(ttl)
macs = input().split()
routers = len(macs) - 2
dropped = False
for i in range(len(macs) - 1):
    print("link " + str(i + 1) + ": " + macs[i] + " > " + macs[i + 1] + ", " + src + " to " + dst + ", ttl " + str(ttl))
    if i < routers:
        ttl -= 1
        if ttl == 0:
            print("dropped at router " + str(i + 1))
            dropped = True
            break
if not dropped:
    print("delivered")

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: How networks work: layers and packets →