---
title: "The Network Layer: IP and Routing"
book: "University Computer Science — Year 2"
subject: computer-science
language: en
chapter: 18
exercises: 12
source: https://one-course.com/books/computer-science/4/en/chapter/18-the-network-layer-ip-and-routing
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 18 — The Network Layer: IP and Routing

A packet leaves the laptop at the library for a server at the far end of town. Each [router](#def-b2-network-layer-routing) on the way takes one off a counter in the packet, and the [router](#def-b2-network-layer-routing) that brings it to zero sends back a note. Sending packets with counters 1, 2, 3, … therefore reveals the path, one [router](#def-b2-network-layer-routing) at a time:

```
$ python traceroute_town.py
from 203.0.113.25 (Library) to the server at 203.0.113.241 (Lighthouse Café)
 1  198.51.100.3    Library            time exceeded
 2  198.51.100.1    Town Square        time exceeded
 3  198.51.100.23   North Bridge       time exceeded
 4  198.51.100.10   River Park         time exceeded
 5  198.51.100.2    Station            time exceeded
 6  198.51.100.11   Hill Park          time exceeded
 7  198.51.100.6    Market Hall        time exceeded
 8  198.51.100.12   Museum             time exceeded
 9  198.51.100.30   Lighthouse Café    time exceeded
10  203.0.113.241   server             reply from the server
```

***Output 18.1.** The town’s network, traced (a simulation, with one [router](#def-b2-network-layer-routing) at each place of the town).*

Nine [routers](#def-b2-network-layer-routing), then the server: the laptop knew none of them, and each [router](#def-b2-network-layer-routing) chose the next one on its own. The [link layer](https://one-course.com/books/computer-science/4/en/chapter/17-the-link-layer#def-b2-link-layer-frame) of [Chapter 17](https://one-course.com/books/computer-science/4/en/chapter/17-the-link-layer#ch-b2-link-layer) carries a frame across one link; the *network layer* carries a packet across many, from any machine to any other. This chapter covers its addresses, how a [router](#def-b2-network-layer-routing) chooses where a packet goes next, and how [routers](#def-b2-network-layer-routing) learn the routes in the first place.

**You already know.**

Book 2: an IPv4 address is four numbers from 0 to 255; a mask says which part names the network; a [routing](#def-b2-network-layer-routing) table, read by hand, tells a [router](#def-b2-network-layer-routing) where to send a packet, and [routers](#def-b2-network-layer-routing) learn routes either from their neighbours’ distances or from a map of the whole network. Year 1: Dijkstra’s algorithm and the Bellman–Ford algorithm compute shortest paths. [Chapter 17](https://one-course.com/books/computer-science/4/en/chapter/17-the-link-layer#ch-b2-link-layer): the [Internet checksum](https://one-course.com/books/computer-science/4/en/chapter/17-the-link-layer#def-b2-link-layer-inet-checksum); frames, MAC addresses and ARP.

## 18.1 Addresses and prefixes

An IPv4 address is a 32-bit number, written as four bytes in decimal: `203.0.113.77` is the number whose bits are

$$
11001011\;00000000\;01110001\;01001101 .
$$

Addresses are handed out in blocks that share their first bits.

**Definition 18.1 (Prefix).**

A *prefix* $a/p$, with $0 \le p \le 32$, is the set of addresses whose first $p$ bits are those of $a$. Its *mask* is the 32-bit number made of $p$ ones then $32 - p$ zeros. An address $x$ belongs to $a/p$ exactly when $x \mathbin{\&} \text{mask} = a \mathbin{\&} \text{mask}$; that common value is the *network address*, and the address with the $32 - p$ last bits all ones is the *broadcast address*.

![The address 203.0.113.77 in the prefix /26: the first 26 bits name the network, the last 6 a machine in it. The mask is 255.255.255.192.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-network-layer/fig-a18c26fb1588.svg)

*The address 203.0.113.77 in the [prefix](#def-b2-network-layer-prefix) /26: the first 26 bits name the network, the last 6 a machine in it. The mask is 255.255.255.192.*

```python
def mask(length):
    return (0xFFFFFFFF << (32 - length)) & 0xFFFFFFFF     # length ones, then zeros


def network(addr, length):
    return addr & mask(length)


def broadcast(addr, length):
    return network(addr, length) | (~mask(length) & 0xFFFFFFFF)
```

***Listing 18.1.** The mask, the network and the broadcast address code/bachelor-2/18-network-layer/listings/cidr.py*

```
$ python cidr.py
203.0.113.77/26    mask 255.255.255.192 network 203.0.113.64   broadcast 203.0.113.127  hosts 62
198.51.100.200/28  mask 255.255.255.240 network 198.51.100.192 broadcast 198.51.100.207 hosts 14
192.0.2.5/30       mask 255.255.255.252 network 192.0.2.4      broadcast 192.0.2.7      hosts 2
11001011000000000111000101001101
```

***Output 18.2.** Three [prefixes](#def-b2-network-layer-prefix), each checked against Python’s `ipaddress`.*

**Method 18.2 (Subnet arithmetic).**

A [prefix](#def-b2-network-layer-prefix) $/p$ holds $2^{32-p}$ addresses, of which $2^{32-p} - 2$ can name machines (the network and broadcast addresses are kept). To split $a/p$ into $2^k$ equal subnets, extend the [prefix](#def-b2-network-layer-prefix) by $k$ bits: the subnets are $a + i
\cdot 2^{32-p-k}$ over $/(p + k)$, for $i = 0, \dots, 2^k - 1$. To find the smallest [prefix](#def-b2-network-layer-prefix) for $h$ machines, take the least $s$ with $2^s - 2 \ge h$: the [prefix](#def-b2-network-layer-prefix) is $/(32 - s)$.

Some blocks are set aside. Every address printed in this chapter comes from the three blocks reserved for documentation, `192.0.2.0/24`, `198.51.100.0/24` and `203.0.113.0/24`, except for the private blocks `10.0.0.0/8`, `172.16.0.0/12` and `192.168.0.0/16`, which any home or company may use inside its own network and which never appear on the Internet itself ([Section 18.3](#sec-18-3)).

**History.**

$2^{32}$ is about 4.3 billion addresses, fewer than the machines that want one. On 3 February 2011 the body that hands out address blocks gave its last five blocks of $2^{24}$ addresses, one to each regional registry, and had none left. Address translation ([Section 18.3](#sec-18-3)) and IPv6 ([Section 18.5](#sec-18-5)) are the two answers.

## 18.2 Forwarding

**Definition 18.3 (Router, forwarding, routing).**

A *router* is a machine with interfaces on several links that passes packets from one to another. It does two different jobs. *Forwarding* is what it does for each packet, millions of times a second: look at the destination address and send the packet out of one interface. *Routing* is how it fills the table it forwards with, by exchanging messages with other routers ([Section 18.6](#sec-18-6)).

**Definition 18.4 (Forwarding table, longest-prefix match).**

A *forwarding table* is a list of [prefixes](#def-b2-network-layer-prefix), each with a next hop. A packet for address $x$ goes to the next hop of the *longest* [prefix](#def-b2-network-layer-prefix) of the table that contains $x$ (*longest-prefix match*). The [prefix](#def-b2-network-layer-prefix) `0.0.0.0/0`, which contains every address, is the *default route*.

The longest [prefix](#def-b2-network-layer-prefix) wins because it is the most precise: a provider announces its whole block, and one customer inside it, reached another way, announces its own smaller block. Trying every [prefix](#def-b2-network-layer-prefix) costs one test per entry, and backbone [routers](#def-b2-network-layer-routing) hold hundreds of thousands of them. A *binary trie* does better: a tree in which each node has a child for bit 0 and one for bit 1, and each [prefix](#def-b2-network-layer-prefix) of length $p$ marks the node reached by its $p$ bits.

```python
class Trie:
    def __init__(self):
        self.root = {}                 # a node: {0: child, 1: child, "hop": port}

    def insert(self, prefix, hop):
        addr, length = parse(prefix)
        node = self.root
        for i in range(length):                # one level per bit of the prefix
            node = node.setdefault(addr >> (31 - i) & 1, {})
        node["hop"] = hop

    def lookup(self, address):
        """The hop of the longest prefix containing address, and the steps taken."""
        addr, _ = parse(address)
        node, best, steps = self.root, self.root.get("hop"), 0
        while steps < 32 and (addr >> (31 - steps) & 1) in node:
            node = node[addr >> (31 - steps) & 1]
            steps += 1
            best = node.get("hop", best)       # a longer prefix overrides
        return best, steps
```

***Listing 18.2.** [Longest-prefix match](#def-b2-network-layer-lpm) on a binary trie code/bachelor-2/18-network-layer/listings/lpm_trie.py*

![The trie of the table 0, 01 3, 1 1, 101 2 (shaded nodes carry a next hop). A lookup walks down the bits of the address and remembers the last mark it met.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-network-layer/fig-19d6ac1b8278.svg)

*The trie of the table $\ast \to 0$, $01\ast \to 3$, $1\ast \to 1$, $101\ast \to 2$ (shaded nodes carry a next hop). A lookup walks down the bits of the address and remembers the last mark it met.*

**Proposition 18.5 (Lookup in a trie).**

`lookup` returns the next hop of the longest [prefix](#def-b2-network-layer-prefix) of the table that contains the address, after at most 32 steps.

**Proof.** After $k$ steps the walk is at the node of the address’s first $k$ bits. The node of a [prefix](#def-b2-network-layer-prefix) $a/p$ lies on this path exactly when the first $p$ bits of the address are those of $a$, that is, when the [prefix](#def-b2-network-layer-prefix) contains the address. The walk passes the marked nodes of all these [prefixes](#def-b2-network-layer-prefix) in order of length, keeping the last, and stops only when the path leaves the trie, below which no node is marked, or after 32 bits. So it returns the longest. Each step consumes one bit of a 32-bit address. ∎

```
$ python lpm_trie.py
198.51.100.7    -> port 1            (24 steps)
198.51.100.200  -> port 2            (25 steps)
203.0.113.77    -> port 4            (26 steps)
203.0.113.5     -> port 3            (25 steps)
192.0.2.1       -> port 0 (default)  (5 steps)
```

***Output 18.3.** Five lookups in a table of five [prefixes](#def-b2-network-layer-prefix).*

```
$ python lpm_bench.py
prefixes  linear (us/lookup)  trie (us/lookup)
     250                 218               1.9
    1000                 879               2.4
    4000                3581               2.9
```

***Output 18.4.** Lookup time against table size on the laptop, for 500 random addresses.*

The linear scan’s time grows with the table; the trie’s barely moves. Hardware [routers](#def-b2-network-layer-routing) use compressed tries, and special memories that compare an address with every [prefix](#def-b2-network-layer-prefix) at once.

### 18.2.1 The IPv4 header

![The IPv4 header without options: 20 bytes, five rows of 32 bits. IHL is the header’s length in rows; the protocol says what the payload is (6 for TCP, 17 for UDP).](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-network-layer/fig-483eeeb5df7c.svg)

*The IPv4 header without options: 20 bytes, five rows of 32 bits. IHL is the header’s length in rows; the protocol says what the payload is (6 for TCP, 17 for UDP).*

Every packet starts with this header. Two fields change at every [router](#def-b2-network-layer-routing).

**Definition 18.6 (Time to live).**

The *time to live* of a packet is a counter in its header that every [router](#def-b2-network-layer-routing) decreases by one; a [router](#def-b2-network-layer-routing) that brings it to zero destroys the packet, so that a packet caught in a [routing](#def-b2-network-layer-routing) loop cannot circle forever, and sends back a “time exceeded” message.

That message is what [Output 18.1](#out-b2-network-layer-hook) used. The *header [checksum](https://one-course.com/books/computer-science/4/en/chapter/17-the-link-layer#def-b2-link-layer-edc)*, the [Internet checksum](https://one-course.com/books/computer-science/4/en/chapter/17-the-link-layer#def-b2-link-layer-inet-checksum) of [Chapter 17](https://one-course.com/books/computer-science/4/en/chapter/17-the-link-layer#ch-b2-link-layer) computed over the header with the field taken as 0, must then be computed again.

```python
def forward(h):
    """What a router does: check, take one off the time to live, fix the checksum."""
    assert ones_sum(h) == 0xFFFF, "damaged header: drop it"
    h = bytearray(h)
    h[8] -= 1
    h[10:12] = b"\0\0"
    h[10:12] = (~ones_sum(h) & 0xFFFF).to_bytes(2, "big")
    return bytes(h)
```

***Listing 18.3.** What a [router](#def-b2-network-layer-routing) does to each header code/bachelor-2/18-network-layer/listings/ipv4_header.py*

```
$ python ipv4_header.py
header: 45 00 00 20 00 01 40 00 40 11 d4 8a c6 33 64 03 cb 00 71 0a
version 4, length 5 words, total 32 bytes, ttl 64, protocol 17, checksum d48a
from 198.51.100.3 to 203.0.113.10
after one router: ttl 63, checksum d58a, sum ffff
```

***Output 18.5.** A header built, decoded and forwarded once.*

The [time to live](#def-b2-network-layer-ttl) dropped from 64 (`0x40`) to 63, and the [checksum](https://one-course.com/books/computer-science/4/en/chapter/17-the-link-layer#def-b2-link-layer-edc) went up by `0x0100`, the same amount in the same byte. Error reports such as “time exceeded” or “destination unreachable” travel in small packets of their own protocol, ICMP, which is also what `ping` sends.

## 18.3 Address translation

A home has one public address and many machines with private ones. Its [router](#def-b2-network-layer-routing) translates.

**Definition 18.7 (Network address and port translation).**

A *NAT* [router](#def-b2-network-layer-routing) rewrites each packet that leaves the private network: the private source address and port become its own public address and a port it chooses, and it records the pair in a table. A packet that comes back to that public port is rewritten the other way and delivered. A packet that arrives for a port with no entry has nobody to go to, and is dropped.

```python
class NAT:
    def __init__(self):
        self.out, self.back, self.next_port = {}, {}, 40000

    def outbound(self, src, sport, dst, dport):
        key = (src, sport)
        if key not in self.out:                # a new conversation: a new public port
            self.out[key], self.back[self.next_port] = self.next_port, key
            self.next_port += 1
        return PUBLIC, self.out[key], dst, dport

    def inbound(self, src, sport, dport):
        if dport not in self.back:
            return None                        # nobody inside asked: dropped
        inside, iport = self.back[dport]
        return src, sport, inside, iport
```

***Listing 18.4.** The translation table code/bachelor-2/18-network-layer/listings/nat_sim.py*

```
$ python nat_sim.py
out 192.168.1.10:50000 -> 198.51.100.20:80   becomes 203.0.113.7:40000 -> 198.51.100.20:80
out 192.168.1.11:50000 -> 198.51.100.20:80   becomes 203.0.113.7:40001 -> 198.51.100.20:80
out 192.168.1.10:50001 -> 198.51.100.20:80   becomes 203.0.113.7:40002 -> 198.51.100.20:80
in  198.51.100.20:80 -> 203.0.113.7:40001   delivered to 192.168.1.11:50000
in  198.51.100.20:80 -> 203.0.113.7:40007   dropped: no entry
```

***Output 18.6.** Two machines inside, one address outside.*

![One connection through a NAT. The server sees only the router’s address; the table maps the router’s port back to the machine inside.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-network-layer/fig-17df5a31088d.svg)

*One connection through a [NAT](#def-b2-network-layer-nat). The server sees only the [router](#def-b2-network-layer-routing)’s address; the table maps the [router](#def-b2-network-layer-routing)’s port back to the machine inside.*

Translation saved the Internet from running out of addresses, at a price. A machine inside cannot be reached until it has spoken first, so two machines both behind [NATs](#def-b2-network-layer-nat) cannot simply connect to each other; a protocol that writes addresses inside its messages sees them unchanged while the headers are rewritten; and the [router](#def-b2-network-layer-routing) must keep state for every conversation, which the end-to-end design of the Internet had avoided.

## 18.4 Fragmentation

**Definition 18.8 (Maximum transmission unit, fragmentation).**

The *maximum transmission unit* (MTU) of a link is its largest frame payload (1500 bytes on Ethernet). *Fragmentation* cuts a packet larger than the next link’s MTU into *fragments*, each with its own header, which the destination puts back together.

An IPv4 [router](#def-b2-network-layer-routing) fragments a packet whose “don’t fragment” flag is not set.

```
$ python fragment.py
payload 4000 bytes, MTU 1500:
  offset   0 (byte    0)  1480 bytes  MF=1
  offset 185 (byte 1480)  1480 bytes  MF=1
  offset 370 (byte 2960)  1040 bytes  MF=0
payload 4000 bytes, MTU 576:
  offset   0 (byte    0)   552 bytes  MF=1
  offset  69 (byte  552)   552 bytes  MF=1
  offset 138 (byte 1104)   552 bytes  MF=1
  offset 207 (byte 1656)   552 bytes  MF=1
  offset 276 (byte 2208)   552 bytes  MF=1
  offset 345 (byte 2760)   552 bytes  MF=1
  offset 414 (byte 3312)   552 bytes  MF=1
  offset 483 (byte 3864)   136 bytes  MF=0
```

***Output 18.7.** 4000 bytes of payload through links of [MTU](#def-b2-network-layer-fragmentation) 1500 and 576.*

Each fragment keeps the packet’s identification; its *offset* says where its data starts, in units of 8 bytes, which is why every fragment but the last carries a multiple of 8 bytes; the *more fragments* flag is 1 on all but the last. One lost fragment loses the whole packet. Modern hosts avoid [fragmentation](#def-b2-network-layer-fragmentation): they send with “don’t fragment” set and lower their packet size when a [router](#def-b2-network-layer-routing) reports that a packet was too big. Every host must accept packets of up to 576 bytes.

## 18.5 IPv6

**Definition 18.9 (IPv6 address).**

An *IPv6 address* is an address of 128 bits, written in the text form given below.

$2^{128}$ addresses are enough to give every machine a public one. The header is simpler than IPv4’s: a fixed 40 bytes with version, traffic class, flow label, payload length, next header (the protocol field), hop limit (the [time to live](#def-b2-network-layer-ttl)), and the two addresses. There is no header [checksum](https://one-course.com/books/computer-science/4/en/chapter/17-the-link-layer#def-b2-link-layer-edc), since the link and transport layers each have their own, and [routers](#def-b2-network-layer-routing) never fragment: only the sender does, and every link must carry at least 1280 bytes.

An address is written as eight groups of 16 bits in hexadecimal, separated by colons. Leading zeros in a group are dropped, and one run of at least two groups of zeros, the longest (the first if two are equally long), is written `::`. Letters are in lowercase. The [prefix](#def-b2-network-layer-prefix) `2001:db8::/32` is reserved for documentation.

```
$ python ipv6_text.py
2001:db8::1                   2001:0db8:0000:0000:0000:0000:0000:0001
2001:db8:0:0:1::              2001:0db8:0000:0000:0001:0000:0000:0000
::1                           0000:0000:0000:0000:0000:0000:0000:0001
2001:DB8:0:0:8:800:200C:417A  2001:0db8:0000:0000:0008:0800:200c:417a
```

***Output 18.8.** Short forms expanded to eight groups, as `ipaddress` does.*

## 18.6 Routing

[Forwarding tables](#def-b2-network-layer-lpm) are filled by [routing](#def-b2-network-layer-routing) protocols. Inside one network, [routers](#def-b2-network-layer-routing) use one of two families, both computing shortest paths in the graph of [routers](#def-b2-network-layer-routing) and links, where each link has a cost.

### 18.6.1 Distance vector

**Definition 18.10 (Distance-vector routing).**

In *distance-vector routing*, each [router](#def-b2-network-layer-routing) knows only its neighbours and the cost of its links to them, and repeatedly sends its table of distances to its neighbours, keeping for each destination the neighbour that offers the shortest total. A *count to infinity* is the slow rise of distances after a failure; *split horizon* is a remedy, below.

Periodically, every [router](#def-b2-network-layer-routing) sends its table of distances to its neighbours, and rebuilds its own table from theirs: the distance to $d$ is the least, over neighbours $v$, of the link cost to $v$ plus $v$’s distance to $d$, and the next hop is that $v$. This is the Bellman–Ford algorithm, run by all the [routers](#def-b2-network-layer-routing) together.

```python
def dv_round(graph, tables, inf=INF, poison=False):
    """Every router rebuilds its table from its neighbours' tables of the last round."""
    new = {}
    for u in sorted(graph):
        t = {u: (0, u)}
        for v in sorted(graph[u]):
            for d, (dist, hop) in sorted(tables[v].items()):
                if poison and hop == u and d != v:
                    dist = inf                 # poisoned reverse: "not via me"
                cand = min(dist + graph[u][v], inf)
                if d not in t or cand < t[d][0]:
                    t[d] = (cand, v)
        new[u] = t
    return new
```

***Listing 18.5.** One synchronous round of distance vector code/bachelor-2/18-network-layer/listings/distance_vector.py*

```
$ python distance_vector.py
round 1  A: A0 B1 C4  B: A1 B0 C2  C: A4 B2 C0 D1  D: C1 D0
round 2  A: A0 B1 C3 D5  B: A1 B0 C2 D3  C: A3 B2 C0 D1  D: A5 B3 C1 D0
round 3  A: A0 B1 C3 D4  B: A1 B0 C2 D3  C: A3 B2 C0 D1  D: A4 B3 C1 D0
round 4  A: A0 B1 C3 D4  B: A1 B0 C2 D3  C: A3 B2 C0 D1  D: A4 B3 C1 D0
```

***Output 18.9.** Four [routers](#def-b2-network-layer-routing), links A–B 1, B–C 2, A–C 4, C–D 1; the tables after each round. Some lines are left out.*

After round 1 each [router](#def-b2-network-layer-routing) knows its neighbours; A reaches C at cost 4 directly. In round 2 it hears B’s distance 2 to C and switches to the path through B, cost 3. After round 3 nothing changes.

**Theorem 18.11 (Convergence).**

Let the network have $n$ [routers](#def-b2-network-layer-routing) and positive link costs, and let every table start with only the [router](#def-b2-network-layer-routing) itself, at distance 0. After round $k$ of synchronous distance vector, each [router](#def-b2-network-layer-routing)’s distance to each destination is the least cost of a path to it with at most $k$ links. Hence after $n - 1$ rounds every distance is the shortest-path distance, and no table changes after that.

The proof, by induction on $k$, is [Exercise 18.8](#exo-b2-network-layer-8). On the town’s 30 [routers](#def-b2-network-layer-routing) the tables stop changing after 8 rounds, the most links on any shortest path, and agree with Dijkstra’s algorithm run at each [router](#def-b2-network-layer-routing):

```
$ python town_network.py
30 routers, 53 links
distance vector: 8 changing rounds; equals Dijkstra: True
```

***Output 18.10.** Distance vector against link state on the town’s network. Some lines are left out.*

Good news travels fast. Bad news does not. Take a separate line A–B–C, both links of cost 1. When the link from B to C fails, B no longer reaches C directly, but A still announces C at distance 2, through B. B takes that route, at distance 3; A then hears 3 from B, and so on:

```
$ python distance_vector.py
line A-B-C (costs 1), link B-C fails; distances to C:
round  1  A  2 via B  B  3 via A
round  2  A  4 via B  B  3 via A
round  3  A  4 via B  B  5 via A
round  4  A  6 via B  B  5 via A
round  5  A  6 via B  B  7 via A
round  6  A  8 via B  B  7 via A
round  7  A  8 via B  B  9 via A
round  8  A 10 via B  B  9 via A
round  9  A 10 via B  B 11 via A
round 10  A 12 via B  B 11 via A
round 11  A 12 via B  B 13 via A
round 12  A 14 via B  B 13 via A
round 13  A 14 via B  B 15 via A
round 14  A 16 via B  B 15 via A
round 15  A 16 via B  B 16 via A
```

***Output 18.11.** The count to infinity. Some lines are left out.*

**Proposition 18.12 (Count to infinity).**

In this situation, where A’s only route to C goes through B and B’s through A, the larger of their two distances to C grows by exactly the cost of the link A–B at each round, until it reaches the value taken as infinity.

**Proof.** Each one’s only neighbour with a route to C is the other, so with $c$ the link cost, $a_{r} = b_{r-1} + c$ and $b_r =
a_{r-1} + c$ (capped at infinity). Hence $\max(a_r, b_r) = \max(a_{r-1}, b_{r-1}) + c$. ∎

![A and B take turns raising their distance to C by 2, each believing the other still has a route. 15 rounds pass before both declare C unreachable.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-network-layer/fig-7eb9126b50f4.svg)

*A and B take turns raising their distance to C by 2, each believing the other still has a route. 15 rounds pass before both declare C unreachable.*

That is why distance-vector protocols take a small number for infinity: RIP, the classic one, uses 16 and sends its tables every 30 seconds, so a count to infinity could take minutes. A remedy, *split horizon with poisoned reverse*, has a [router](#def-b2-network-layer-routing) tell the neighbour it routes through that its distance is infinite; it cures this two-router loop, but not every loop ([Exercise 18.10](#exo-b2-network-layer-10)).

### 18.6.2 Link state

**Definition 18.13 (Link-state routing).**

In *link-state routing*, each [router](#def-b2-network-layer-routing) floods to every other [router](#def-b2-network-layer-routing) a description of its own links, so that every [router](#def-b2-network-layer-routing) holds the same map of the whole network, and each computes its shortest paths from itself with Dijkstra’s algorithm.

When a link fails, the two [routers](#def-b2-network-layer-routing) at its ends flood the news, and every [router](#def-b2-network-layer-routing) computes again, once. OSPF, the common link-state protocol, works this way. The cost is that every [router](#def-b2-network-layer-routing) stores the whole map and runs Dijkstra on each change; the gain is fast, loop-free convergence.

```python
def dijkstra(graph, source):
    """Distance and first hop from source to every reachable router."""
    dist, first = {source: 0}, {source: source}
    heap, done = [(0, source)], set()
    while heap:
        d, u = heapq.heappop(heap)
        if u in done:
            continue
        done.add(u)
        for v, c in sorted(graph[u].items()):
            if v not in dist or d + c < dist[v]:
                dist[v] = d + c
                first[v] = v if u == source else first[u]   # the way out of source
                heapq.heappush(heap, (dist[v], v))
    return dist, first
```

***Listing 18.6.** Each [router](#def-b2-network-layer-routing)’s computation in link state: Dijkstra, keeping the first hop code/bachelor-2/18-network-layer/listings/link_state.py*

### 18.6.3 Between operators

The Internet is a network of networks.

**Definition 18.14 (Autonomous system, path-vector routing).**

An *autonomous system* is a set of [routers](#def-b2-network-layer-routing) under one technical administration, which uses its own [routing](#def-b2-network-layer-routing) protocol inside. In *path-vector routing*, each announcement of a [prefix](#def-b2-network-layer-prefix) carries the list of autonomous systems it passed through, so that a system that finds itself in the list knows there is a loop and ignores the announcement.

Between [autonomous systems](#def-b2-network-layer-as) runs BGP, a path-vector protocol. The choice among routes is a matter of policy (which neighbour is a customer, which one is paid) rather than of shortest paths.

![An Interface Message Processor, one of the first packet switches: in the network that grew into the Internet, each of these minicomputers forwarded packets between its host computers and its neighbours. Photograph: ArnoldReinhold, CC BY 4.0.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-network-layer/img-771fde6f7182.jpg)

*An Interface Message Processor, one of the first packet switches: in the network that grew into the Internet, each of these minicomputers forwarded packets between its host computers and its neighbours. Photograph: ArnoldReinhold, CC BY 4.0.*

## 18.7 Exercises

**Exercise 18.1 ★.**

Give the mask, network address, broadcast address and number of host addresses of `198.51.100.77/27` and of `192.0.2.130/25`.

**Solution of Exercise 18.1.**

`198.51.100.77/27`: mask 255.255.255.224; $77 = 64 + 13$ and a `/27` block has 32 addresses, so the network is 198.51.100.64, the broadcast 198.51.100.95, and $32 - 2 = 30$ hosts. `192.0.2.130/25`: mask 255.255.255.128, network 192.0.2.128, broadcast 192.0.2.255, 126 hosts.

**Exercise 18.2 ★.**

This mask is one bit short. What [prefix](#def-b2-network-layer-prefix) does it really compute, and is the answer to the membership test right?

```python
def mask_wrong(length):
    return (0xFFFFFFFF << (32 - length + 1)) & 0xFFFFFFFF
```

***Listing 18.7.** A shifted mask code/bachelor-2/18-network-layer/listings/exo_mask.py*

```
$ python exo_mask.py
mask    255.255.255.128
network 203.0.113.0
contains 203.0.113.10: True
```

***Output 18.12.** For 203.0.113.77/26.*

**Solution of Exercise 18.2.**

The shift is by $32 - p + 1$ instead of $32 - p$, so the mask has $p - 1$ ones: for `/26` it is the mask of a `/25`, 255.255.255.128, and the network comes out as 203.0.113.0. The membership test answers for that `/25`: 203.0.113.10 is in 203.0.113.0/25, hence `True`, but it is not in 203.0.113.64/26. The answer is wrong, and looks plausible because both [prefixes](#def-b2-network-layer-prefix) start alike. Testing against `ipaddress`, as `cidr.py` does, catches it on the first address.

**Exercise 18.3 ★.**

Write `contains(prefix, address)` for [prefixes](#def-b2-network-layer-prefix) and addresses in text, using `cidr.py`.

**Solution of Exercise 18.3.**

```python
def contains(prefix, address):
    net, length = parse(prefix)
    addr, _ = parse(address)
    return addr & mask(length) == net & mask(length)
```

*Membership in a [prefix](#def-b2-network-layer-prefix) code/bachelor-2/18-network-layer/exercises/contains.py*

Masking both sides makes the function correct even for a [prefix](#def-b2-network-layer-prefix) written with host bits set, such as `203.0.113.77/26`. The test compares it with `ipaddress` on random addresses and lengths, 0 and 32 included.

**Exercise 18.4 ★.**

How many machines can a `/26` hold? Split `203.0.113.0/24` into the smallest [prefixes](#def-b2-network-layer-prefix) for four offices of 50, 20, 10 and 2 machines, without overlap.

**Solution of Exercise 18.4.**

A `/26` holds $2^6 - 2 = 62$ machines. The offices need $s$ with $2^s - 2$ at least 50, 20, 10 and 2: $s = 6, 5,
4, 2$, that is a `/26`, a `/27`, a `/28` and a `/30`. Placing the largest first keeps each block aligned on its size: 203.0.113.0/26, 203.0.113.64/27, 203.0.113.96/28 and 203.0.113.112/30, which leaves 203.0.113.116 to 203.0.113.255 free.

**Exercise 18.5 ★★.**

A [router](#def-b2-network-layer-routing) has the routes `0.0.0.0/0` $\to$ W, `198.51.100.0/24` $\to$ X, `198.51.100.64/26` $\to$ Y and `198.51.100.96/27` $\to$ Z. Where do packets for `198.51.100.70`, `198.51.100.100`, `198.51.100.130` and `192.0.2.1` go?

**Solution of Exercise 18.5.**

`198.51.100.70` is in the `/24` and the `/26` (64 to 127), not in the `/27` (96 to 127): Y. `198.51.100.100` is in all three: Z, the longest. `198.51.100.130` is only in the `/24`: X. `192.0.2.1` matches only the default route: W.

**Exercise 18.6 ★★.**

After the [time to live](#def-b2-network-layer-ttl) is lowered, this [router](#def-b2-network-layer-routing) computes the [checksum](https://one-course.com/books/computer-science/4/en/chapter/17-the-link-layer#def-b2-link-layer-edc) without first clearing the field. What does the next [router](#def-b2-network-layer-routing) see, and how does the error show in the output?

```python
h = bytearray(header("198.51.100.3", "203.0.113.10", payload_len=12))
h[8] -= 1                                      # one hop: the time to live goes down
h[10:12] = (~ones_sum(h) & 0xFFFF).to_bytes(2, "big")    # old checksum summed too
print(f"checksum written {h[10:12].hex()}, receiver's sum {ones_sum(h):04x}")
```

***Listing 18.8.** A [checksum](https://one-course.com/books/computer-science/4/en/chapter/17-the-link-layer#def-b2-link-layer-edc) over itself code/bachelor-2/18-network-layer/listings/exo_hdrsum.py*

```
$ python exo_hdrsum.py
checksum written 0100, receiver's sum 2b75
```

***Output 18.13.** The receiver’s sum.*

**Solution of Exercise 18.6.**

The new [checksum](https://one-course.com/books/computer-science/4/en/chapter/17-the-link-layer#def-b2-link-layer-edc) is the complement of a sum that includes the old [checksum](https://one-course.com/books/computer-science/4/en/chapter/17-the-link-layer#def-b2-link-layer-edc), so it is not the complement of the sum of the other words. The next [router](#def-b2-network-layer-routing) adds all ten words and gets `2b75` instead of `ffff`: it takes the header for damaged and drops the packet. Every packet through this [router](#def-b2-network-layer-routing) is lost, which makes the bug obvious in practice, and the output shows why: the receiver’s sum is the check. Clearing the field first, as `forward` does, fixes it.

**Exercise 18.7 ★★.**

Write `aggregate(prefixes)`, which replaces a set of [prefixes](#def-b2-network-layer-prefix) with the same next hop by the fewest [prefixes](#def-b2-network-layer-prefix) covering exactly the same addresses: drop a [prefix](#def-b2-network-layer-prefix) inside another, merge two halves of a [prefix](#def-b2-network-layer-prefix). Test it against `ipaddress.collapse_addresses`.

**Solution of Exercise 18.7.**

```python
def aggregate(prefixes):
    """Prefixes with the same next hop, as text; returns a minimal equivalent list."""
    nets = {(n & mask(p), p) for n, p in map(parse, prefixes)}
    changed = True
    while changed:
        changed = False
        for n, p in sorted(nets, key=lambda x: -x[1]):
            if (n, p) not in nets:
                continue
            if any(q < p and n & mask(q) == m for m, q in nets):
                nets.discard((n, p))           # inside a shorter prefix: redundant
                changed = True
                continue
            sibling = n ^ (1 << (32 - p)) if p > 0 else None
            if sibling is not None and (sibling, p) in nets:
                nets -= {(n, p), (sibling, p)}
                nets.add((n & mask(p - 1), p - 1))   # two halves make the whole
                changed = True
    return [f"{dotted(n)}/{p}" for n, p in sorted(nets)]
```

*Aggregating [prefixes](#def-b2-network-layer-prefix) code/bachelor-2/18-network-layer/exercises/aggregate.py*

Two rules are applied until neither applies: a [prefix](#def-b2-network-layer-prefix) inside a shorter one of the set is dropped; two [prefixes](#def-b2-network-layer-prefix) of the same length that differ only in their last bit, the two halves of a [prefix](#def-b2-network-layer-prefix) one bit shorter, are replaced by it. The result covers the same addresses, and it is the fewest [prefixes](#def-b2-network-layer-prefix): in the final set no [prefix](#def-b2-network-layer-prefix) is inside another and no two are siblings, which is exactly the shape of the unique minimal cover. The test compares it with `ipaddress.collapse_addresses` on random sets.

**Exercise 18.8 ★★.**

Prove [Theorem 18.11](#thm-b2-network-layer-dv-converge).

**Solution of Exercise 18.8.**

Write $D_k(u, d)$ for the least cost of a path from $u$ to $d$ with at most $k$ links (infinite if there is none), and assume that the value taken as infinity exceeds every distance. We show by induction on $k$ that after round $k$, the table of $u$ gives $D_k(u, d)$ for every $d$, a destination being absent when the value is infinite.

For $k = 0$, the only path with no link is the empty path from $u$ to itself: $D_0(u, u) = 0$, and the initial table holds exactly that. Suppose the claim holds after round $k$. A path from $u$ to $d \ne u$ with at most $k + 1$ links starts with a link to some neighbour $v$, followed by a path from $v$ to $d$ with at most $k$ links; so $D_{k+1}(u, d) = \min_v \bigl(c(u, v) + D_k(v, d)\bigr)$, and $D_{k+1}(u, u) = 0$ since costs are positive. Round $k +
1$ computes exactly this minimum from the neighbours’ tables of round $k$, which by hypothesis hold $D_k(v, d)$.

With positive costs a shortest path visits no [router](#def-b2-network-layer-routing) twice, so it has at most $n - 1$ links: $D_{n-1}(u, d)$ is the shortest distance, and $D_k = D_{n-1}$ for every $k \ge n - 1$. The distances therefore stop changing after at most $n - 1$ rounds; the next hops, chosen by the same rule from the same values, stop with them.

**Exercise 18.9 ★★.**

Write `fragment(payload_len, mtu)`, returning the offset, size and flag of each fragment, check it against [Output 18.7](#out-b2-network-layer-fragment), and give by hand the fragments of 3000 bytes for an [MTU](#def-b2-network-layer-fragmentation) of 1006. Why must every fragment but the last carry a multiple of 8 bytes?

**Solution of Exercise 18.9.**

```python
def fragment(payload_len, mtu, header=20):
    """(offset in 8-byte units, data bytes, more-fragments flag) for each fragment."""
    per = (mtu - header) // 8 * 8              # all but the last: a multiple of 8
    out, start = [], 0
    while start < payload_len:
        size = min(per, payload_len - start)
        out.append((start // 8, size, start + size < payload_len))
        start += size
    return out
```

*[Fragmentation](#def-b2-network-layer-fragmentation) code/bachelor-2/18-network-layer/listings/fragment.py*

With an [MTU](#def-b2-network-layer-fragmentation) of 1006, each fragment carries at most $(1006 - 20)$ rounded down to a multiple of 8, that is 984 bytes: fragments of 984, 984, 984 and 48 bytes, at offsets 0, 123, 246 and 369 (in units of 8 bytes), the flag MF set on all but the last. The offset field has 13 bits and counts 8-byte units, so offsets up to $(2^{13} - 1) \times 8 =
65\,528$ bytes cover any packet, whose total length is at most $65\,535$ bytes; this saves 3 bits of header, and requires every fragment but the last to end on a multiple of 8.

**Exercise 18.10 ★★★.**

Add split horizon with poisoned reverse to the rounds of distance vector. Show that it cures the line A–B–C when B–C fails, but not a triangle A, B, C with D behind C, when C–D fails. Explain the second case.

**Solution of Exercise 18.10.**

```
$ python poison.py
line A-B-C, B-C fails              plain             every router at 16 after 15 rounds
line A-B-C, B-C fails              poisoned reverse  every router at 16 after 2 rounds
triangle A-B-C plus D, C-D fails   plain             every router at 16 after 15 rounds
triangle A-B-C plus D, C-D fails   poisoned reverse  every router at 16 after 15 rounds
```

***Output 18.15.** Plain and poisoned, after the failure.*

The change is one line in `dv_round`: when $v$’s route to $d$ goes through $u$, $u$ reads it as infinite (`poison=True`). On the line, A routes to C through B, so it tells B “infinity”; B, having lost its link, has no route left and says so at once, and both reach 16 in 2 rounds. In the triangle, after C–D fails, A and B both route to D through C, so each poisons only its announcement to C, and C has no route left. But A still tells B “D at 2”: A’s route goes through C, not through B, so nothing is poisoned. In round 2, A and B each take D at 3 through the other. In round 3 they poison each other and drop to 16, but C hears A’s 3, which does not go through C, and takes D at 4 through A; in round 4, B takes 5 through C. The stale route travels round the triangle, one hop and one unit per round. Poisoning only stops a [router](#def-b2-network-layer-routing) from echoing a route back to its own next hop, a loop of two; this loop has three, and the [routers](#def-b2-network-layer-routing) count to infinity in 15 rounds, as without it.

**Exercise 18.11 ★★★.**

Compare the cost of a lookup in a trie, in a linear table, and by binary search in a sorted list of [prefixes](#def-b2-network-layer-prefix), which must also handle nested [prefixes](#def-b2-network-layer-prefix). Relate your estimates to [Output 18.4](#out-b2-network-layer-bench).

**Solution of Exercise 18.11.**

A linear table costs one test per [prefix](#def-b2-network-layer-prefix): $n$ tests, as the printed times show (about 0.9 µs per [prefix](#def-b2-network-layer-prefix), four times the time for four times the [prefixes](#def-b2-network-layer-prefix)). A trie costs one step per bit of the longest matching path, at most 32, whatever $n$; its time rises a little with $n$ only because more [prefixes](#def-b2-network-layer-prefix) make longer paths. Binary search does not work directly on nested [prefixes](#def-b2-network-layer-prefix), since the longest match need not be next to the address in sorted order. Each [prefix](#def-b2-network-layer-prefix) is a range of addresses; the $n$ ranges cut the address space into at most $2n + 1$ intervals, each labelled with the longest [prefix](#def-b2-network-layer-prefix) that contains it. A binary search among these intervals costs $\log_2(2n + 1)$ steps, about 13 for 4000 [prefixes](#def-b2-network-layer-prefix), but an update may relabel many intervals, while a trie changes one node.

**Exercise 18.12 ★★★.**

Write `compress(groups)`, which gives the recommended text form of an [IPv6 address](#def-b2-network-layer-ipv6) from its eight groups, and test it against `ipaddress` on many addresses with runs of zeros.

**Solution of Exercise 18.12.**

```python
def compress(groups):
    """Eight 16-bit integers -> the text the standard recommends."""
    best_start, best_len, i = -1, 1, 0         # runs of length 1 are never shortened
    while i < 8:
        if groups[i] == 0:
            j = i
            while j < 8 and groups[j] == 0:
                j += 1
            if j - i > best_len:               # strictly longer: the first one wins
                best_start, best_len = i, j - i
            i = j
        else:
            i += 1
    text = [f"{g:x}" for g in groups]
    if best_start < 0:
        return ":".join(text)
    left = ":".join(text[:best_start])
    right = ":".join(text[best_start + best_len:])
    return left + "::" + right
```

*The recommended text form code/bachelor-2/18-network-layer/exercises/ipv6_compress.py*

The loop finds the longest run of zero groups, taking a run only if it is strictly longer than the best so far, so the first of two equal runs wins and a run of one group (the initial `best_len` is 1) is never shortened. The groups are written in lowercase hexadecimal without leading zeros. The test draws addresses whose groups are often 0, so that ties and runs at either end occur, and compares with `str(ipaddress.IPv6Address(...))`.

## 18.8 Problem: Routing the town’s network

**Problem 18.1.**

Weekend problem — Routing the town’s network

The town puts a [router](#def-b2-network-layer-routing) at each of its 30 places, joined along its 53 roads, and numbers them from the block `198.51.100.0/24`.

**Part I — An addressing plan.**

1. Each [router](#def-b2-network-layer-routing) gets one address, `198.51.100.` $k$ for place $k$ . How many addresses of the block are left?
2. Each place also has a small network of at most 5 machines. What is the smallest [prefix](#def-b2-network-layer-prefix) for one, and how many such [prefixes](#def-b2-network-layer-prefix) fit in a `/24` ?
3. Could the 30 small networks all fit in `198.51.100.0/24` besides the [routers](#def-b2-network-layer-routing) ’ addresses? Justify.
4. The town gets a second block, `203.0.113.0/24` , and gives place $k$ the `/29` that starts at `203.0.113.` $8k$ . Check that the 30 [prefixes](#def-b2-network-layer-prefix) fit, and give the [prefix](#def-b2-network-layer-prefix) of place 12.
5. Write the network and broadcast addresses of that [prefix](#def-b2-network-layer-prefix) .
6. Why does this plan make [forwarding tables](#def-b2-network-layer-lpm) easy to read?

**Part II — Forwarding tables.**

7. In [Output 18.1](#out-b2-network-layer-hook) , which [router](#def-b2-network-layer-routing) forwards the packet to the Town Square [router](#def-b2-network-layer-routing) ?
8. How many entries does a [router](#def-b2-network-layer-routing) ’s table need with one `/29` per place, and how many if the town announces itself to the outside as one [prefix](#def-b2-network-layer-prefix) ?
9. Write the two entries a [router](#def-b2-network-layer-routing) at the edge of town needs for the outside world.
10. A packet for `203.0.113.97` arrives. Which place’s network is it in?
11. Count the steps of a trie lookup for that address in a table of the 30 `/29` s and a default route.
12. Why is the [time to live](#def-b2-network-layer-ttl) set to 64 rather than to the 9 hops the hook needed?

**Part III — Distance vector against link state.**

13. With road lengths as costs, distance vector stops changing after 8 rounds. What does [Theorem 18.11](#thm-b2-network-layer-dv-converge) say the number of rounds is at most, and what does 8 measure?
14. With hop counts as costs, it takes 7 rounds. Why fewer?
15. How many messages does one round of distance vector send in the town’s network?
16. How many link descriptions does each [router](#def-b2-network-layer-routing) store in link state?
17. Estimate the work of one Dijkstra run on 30 [routers](#def-b2-network-layer-routing) and 53 links.
18. Which design would you choose for the town, and why?

**Part IV — A router fails.**

19. The [router](#def-b2-network-layer-routing) at the Lighthouse Café breaks down. Why do the others not learn at once that it is unreachable? `$ python town_network.py hop counts: 7 rounds; farthest from Lighthouse Café: 7 hops round 1: distances to it from 2 to 7 round 2: distances to it from 3 to 7 round 3: distances to it from 4 to 7 round 15: distances to it from 16 to 16 count to infinity: 15 rounds; link state: one recomputation per router` **Output 18.14.** After the failure, with hop counts. Some lines are left out.
20. Explain the first three lines: why does the nearest [router](#def-b2-network-layer-routing) ’s distance go 1, 2, 3, 4?
21. Why does it take 15 rounds, whatever the [router](#def-b2-network-layer-routing) ’s distance before?
22. With RIP’s 30 seconds per round, how long is the café’s network wrongly announced as reachable?
23. What does link state do instead, and how long does it take?
24. State the result: count to infinity, 15 rounds to reach the limit 16, against one recomputation in link state.

**Solution of Problem 18.1.**

**1.** $256 - 30 = 226$ addresses, two of which (`.0` and `.255`) are the network and broadcast addresses if the whole block is one network.

**2.** Five machines plus the network and broadcast addresses need 7 addresses: a `/29` (8 addresses, 6 machines). A `/24` holds $2^{29-24} = 32$ of them.

**3.** No. The [router](#def-b2-network-layer-routing) addresses 1 to 30 fall in the first four `/29`s (0 to 31), which leaves 28 for 30 networks.

**4.** Place $k$ gets $8k$ to $8k + 7$; for $k = 30$ that is 240 to 247, inside the block, and the 30 ranges do not overlap. Place 12: `203.0.113.96/29`.

**5.** Network 203.0.113.96, broadcast 203.0.113.103.

**6.** The place number is the last byte of an address divided by 8: an address tells at once where it is.

**7.** The Library’s [router](#def-b2-network-layer-routing), `198.51.100.3`, the first hop.

**8.** 30 entries, one per place, plus a default route. Seen from outside, the whole town is one entry, `203.0.113.0/24`: aggregation hides the 30 [prefixes](#def-b2-network-layer-prefix).

**9.** `203.0.113.0/24` (and the [routers](#def-b2-network-layer-routing)’ `198.51.100.0/24`) towards the inside, and `0.0.0.0/0` towards the provider.

**10.** $97 = 8 \times 12 + 1$: place 12.

**11.** 29 steps: the walk follows the address’s bits to the node of `203.0.113.96/29` at depth 29, which has no children.

**12.** The [time to live](#def-b2-network-layer-ttl) must exceed the length of any path a packet may need, anywhere on the Internet, not just in town; 64 leaves a wide margin while still killing a looping packet quickly.

**13.** At most $n - 1 = 29$ rounds. The tables stop changing once every shortest path is known, so 8 is the largest number of links on a shortest path (choosing, for each pair, the shortest path with fewest links).

**14.** With hop counts the shortest paths are those with fewest links, and the longest of them has 7 links; with lengths, the shortest path may take more, shorter, links.

**15.** Each [router](#def-b2-network-layer-routing) sends its table to each neighbour: $2 \times 53 = 106$ messages per round.

**16.** The whole map: the 53 links (each described by both of its [routers](#def-b2-network-layer-routing), 106 descriptions).

**17.** With a heap, about $(n + m)\log_2 n \approx (30 + 106) \times 5 \approx 700$ elementary steps: nothing for a [router](#def-b2-network-layer-routing).

**18.** Link state: the map is small, each [router](#def-b2-network-layer-routing) computes its routes in an instant, and a failure costs one flood and one recomputation instead of a count to infinity.

**19.** Distance vector has no message that says “this [router](#def-b2-network-layer-routing) is gone”. The café’s neighbours lose their links to it, but still hear the other neighbours announce routes to it, routes which went through the café’s own link and are now stale.

**20.** The nearest [routers](#def-b2-network-layer-routing) were at 1, directly linked. After the failure their best offer comes from another former neighbour, which announced 1 in the previous round: 2. In the next round every offer is at least 2, so the least distance is 3, and so on: the least distance grows by one link per round, since every route now passes through another [router](#def-b2-network-layer-routing) that believes in an older, shorter one.

**21.** After round $r$, the least distance is $r + 1$ (by the argument of question 20), so all reach 16 when $r
+ 1 = 16$, at round 15, whatever the distances were before: a far [router](#def-b2-network-layer-routing) keeps its distance until the rising minimum $r + 1$ overtakes it, then rises with the rest, and all reach 16 together.

**22.** $15 \times 30$ s, seven and a half minutes, during which packets for the café circle until their [time to live](#def-b2-network-layer-ttl) runs out.

**23.** The café’s neighbours flood the loss of their links; each [router](#def-b2-network-layer-routing) removes them from its map and runs Dijkstra once, finding the café unreachable. It takes the time of one flood, a fraction of a second.

**24.** Count to infinity: 15 rounds to reach the limit 16 on the town’s network, against one recomputation per [router](#def-b2-network-layer-routing) in link state.
