---
title: "Routing"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 32
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/32-routing
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 32 — Routing

A digger cuts a cable between two routers of a network. The packets that used it do not vanish: within seconds or minutes, the routers on either side notice the silence, tell their neighbours, and the packets take another way. Nobody configured that other way by hand. The routers found it themselves, by talking to each other.

This chapter shows the two ways routers do it. In the first, each router knows only distances, and learns them from its neighbours; in the second, each router learns the whole map and computes its own routes with [Dijkstra’s algorithm](https://one-course.com/books/computer-science/2/en/chapter/26-graph-traversals-and-shortest-paths#met-g12-graph-algorithms-dijkstra). Both are simulated on one invented network of seven routers, before and after a link fails, and the first shows a strange failure of its own: [counting to infinity](#def-g12-routing-convergence).

**You already know.**

A router passes each packet to a *[next hop](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table)* found in its [routing table](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table); the whole route is the chain of these local choices (chapter [15](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#ch-g11-network-protocols)). A [weighted graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-directed) has a number on each edge (chapter [9](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#ch-g10-graphs-first-look)). [Dijkstra’s algorithm](https://one-course.com/books/computer-science/2/en/chapter/26-graph-traversals-and-shortest-paths#met-g12-graph-algorithms-dijkstra) finds the shortest paths from one vertex when the weights are not negative (chapter [26](https://one-course.com/books/computer-science/2/en/chapter/26-graph-traversals-and-shortest-paths#ch-g12-graph-algorithms)).

## 32.1 A network as a weighted graph

The routers of a network are the vertices of a [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph), and the links between them its edges. Each link has a *rate*, the number of bits it carries per second. To choose routes, each link also gets a number, its cost.

**Definition 32.1 (Hop count, route cost).**

The *hop count* of a route is its number of links. When each link has a cost, the *route cost* is the sum of the costs of its links. A routing method chooses, for each destination, a route whose hop count, or whose cost, is smallest.

The [hop count](#def-g12-routing-metric) treats every link alike. A cost can prefer fast links: this chapter gives each link the cost $10\,000$ divided by its rate in megabits per second, so a link of $10\,000$ Mbit/s costs $1$, one of $1000$ costs $10$, one of $10$ costs $1000$. The protocol that uses such costs leaves each link’s cost to the network’s administrator; dividing a reference rate by the link’s rate is one way to set them.

```python
"""An invented network of seven routers, with the rate of each link in Mbit/s."""

RATES = {("A", "B"): 1000, ("A", "C"): 100, ("B", "C"): 1000, ("B", "D"): 100,
         ("C", "E"): 10, ("D", "E"): 1000, ("D", "F"): 1000, ("E", "G"): 100,
         ("F", "G"): 1000}
REFERENCE = 10_000                               # Mbit/s: a link this fast costs 1


def graph(cost, down=()):
    """Neighbours of each router with the cost of each link; links in down are cut."""
    g = {}
    for (u, v), rate in RATES.items():
        if (u, v) in down or (v, u) in down:
            continue
        g.setdefault(u, {})[v] = cost(rate)
        g.setdefault(v, {})[u] = cost(rate)
    return dict(sorted(g.items()))


def hops(rate):
    return 1                                     # every link counts the same


def by_rate(rate):
    return REFERENCE // rate                     # faster links cost less


def route(tables, source, target):
    """Follow the next hops from source; tables[r][dest] = (distance, next hop)."""
    path = [source]
    while path[-1] != target:
        path.append(tables[path[-1]][target][1])
    return path
```

***Listing 32.1.** The network of the chapter, and the two ways of costing its links. code/grade-12/11-routing/listings/network.py*

![The invented network: seven routers, nine links, each labelled with its rate in Mbit/s and its cost. Thicker lines are faster links. By hop count, the best route from A to E goes through C, over the slowest link of all.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-routing/fig-1454b9e800e8.svg)

*The invented network: seven routers, nine links, each labelled with its rate in Mbit/s and its cost. Thicker lines are faster links. By [hop count](#def-g12-routing-metric), the best route from A to E goes through C, over the slowest link of all.*

```python
"""Link costs from link rates, and the route they choose against the hop count."""
from link_state import table
from network import RATES, REFERENCE, by_rate, graph, hops, route

for (u, v), rate in RATES.items():
    cost = by_rate(rate)
    print(f"{u} - {v}: {rate:>5} Mbit/s  cost {REFERENCE} // {rate:<5} = {cost:>4}")

for name, cost in [("hop count", hops), ("cost from rates", by_rate)]:
    g = graph(cost)
    tables = {r: table(g, r) for r in g}
    path = route(tables, "A", "E")
    rate = min(RATES.get((u, v)) or RATES[(v, u)] for u, v in zip(path, path[1:]))
    print(f"A to E by {name:15}: {' '.join(path):9} slowest link {rate} Mbit/s")
```

***Listing 32.2.** The cost of each link, and the route from A to E by each measure. code/grade-12/11-routing/listings/ospf_costs.py*

```
$ python ospf_costs.py
A - B:  1000 Mbit/s  cost 10000 // 1000  =   10
A - C:   100 Mbit/s  cost 10000 // 100   =  100
B - C:  1000 Mbit/s  cost 10000 // 1000  =   10
B - D:   100 Mbit/s  cost 10000 // 100   =  100
C - E:    10 Mbit/s  cost 10000 // 10    = 1000
D - E:  1000 Mbit/s  cost 10000 // 1000  =   10
D - F:  1000 Mbit/s  cost 10000 // 1000  =   10
E - G:   100 Mbit/s  cost 10000 // 100   =  100
F - G:  1000 Mbit/s  cost 10000 // 1000  =   10
A to E by hop count      : A C E     slowest link 10 Mbit/s
A to E by cost from rates: A B D E   slowest link 100 Mbit/s
```

***Output 32.1.** Counting hops sends the traffic over a 10 Mbit/s link; costs from rates send it one link further, but ten times faster at its slowest.*

**Definition 32.2 (Routing protocol, distance-vector routing, link-state routing).**

A *routing protocol* is a set of rules by which routers exchange messages so that each can fill its own [routing table](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table). In *distance-vector routing*, each router sends its neighbours its table of distances, and computes its own from theirs. In *link-state routing*, each router sends every other router the list of its own links and their costs; each router then knows the whole [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph), and computes its routes from it.

## 32.2 Distance vectors

A router at first knows only itself. Each *round*, every router receives its neighbours’ tables. If neighbour $n$, reached at cost $c$, says it reaches destination $d$ at distance $x$, then the router can reach $d$ at $c + x$ through $n$. For each destination it keeps the smallest of these sums, and $n$ becomes the [next hop](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table). This is the update of the Bellman–Ford algorithm, run by every router at once on its own data.

```python
"""Distance-vector routing: every round, each router learns its neighbours' tables."""
from network import by_rate, graph


def dv_round(g, tables):
    """One round: each router rebuilds its table from its neighbours' tables."""
    new = {}
    for r in g:
        table = {r: (0, r)}
        for n, cost in g[r].items():
            for dest, (d, _) in tables[n].items():   # n says: I reach dest at d
                if dest not in table or cost + d < table[dest][0]:
                    table[dest] = (cost + d, n)       # better through n
        new[r] = table
    return new


def converge(g, tables, show=None):
    """Run rounds until no table changes; return the tables and the rounds."""
    rounds = 0
    while True:
        new = dv_round(g, tables)
        if new == tables:
            return tables, rounds
        tables, rounds = new, rounds + 1
        if show:
            t = new[show]
            row = "  ".join(f"{d}:{t[d][0]:>4}" if d in t else f"{d}:   -" for d in g)
            print(f"round {rounds:2}  {show} knows  {row}")


if __name__ == "__main__":
    g = graph(by_rate)
    start = {r: {r: (0, r)} for r in g}          # each router knows only itself
    tables, rounds = converge(g, start, show="A")
    print("stable after", rounds, "rounds; A's table (destination: cost, next hop):")
    print("  ".join(f"{d}: {c} {n}" for d, (c, n) in tables["A"].items() if d != "A"))
```

***Listing 32.3.** Distance vectors, round after round, from tables that know nothing. code/grade-12/11-routing/listings/dv_rounds.py*

```
$ python dv_rounds.py
round  1  A knows  A:   0  B:  10  C: 100  D:   -  E:   -  F:   -  G:   -
round  2  A knows  A:   0  B:  10  C:  20  D: 110  E:1100  F:   -  G:   -
round  3  A knows  A:   0  B:  10  C:  20  D: 110  E: 120  F: 120  G:1200
round  4  A knows  A:   0  B:  10  C:  20  D: 110  E: 120  F: 120  G: 130
stable after 4 rounds; A's table (destination: cost, next hop):
B: 10 B  C: 20 B  D: 110 B  E: 120 B  G: 130 B  F: 120 B
```

***Output 32.2.** A’s distances, round by round. News travels one link per round; a first answer, such as $1100$ for E, can be bettered later.*

After round $k$, a router knows the shortest route to each destination among the routes of at most $k$ links (exercise [32.12](#exo-g12-routing-12)). The routes here have at most four links, so four rounds suffice; a fifth changes nothing, and the tables are stable.

**Definition 32.3 (Convergence, counting to infinity).**

A [routing protocol](#def-g12-routing-routing-protocol) has *converged* when no table changes any more and every route is a shortest one. *Counting to infinity* is a slow convergence of [distance-vector routing](#def-g12-routing-routing-protocol) after a failure: routers learn from each other distances that pass through themselves, and raise them a little each round until they reach the value that means “unreachable”.

## 32.3 Bad news travels slowly

Take three routers on a line, A – B – C, counting hops. The stable tables say that B reaches C in $1$ hop and A in $2$, through B. Then the link B – C fails. B no longer hears from C; but A still says “I reach C in $2$”. B cannot know that A’s route goes through B itself, so it believes it: $3$, through A. A then hears $3$ from B, its [next hop](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table), and must update to $4$. The two count up together.

To stop the count, the hop-count protocol sets a ceiling: a distance of $16$ means unreachable, and routes may have at most $15$ hops.

```python
"""Hop-count routing on a line A - B - C, where 16 means unreachable."""
INFINITY = 16


def dv_round(g, tables, split_horizon=False):
    new = {}
    for r in g:
        table = {r: (0, r)}
        for n, cost in g[r].items():
            for dest, (d, via) in tables[n].items():
                if split_horizon and via == r:
                    continue                     # n does not tell r a route through r
                d = min(cost + d, INFINITY)
                if dest not in table or d < table[dest][0]:
                    table[dest] = (d, n)
        new[r] = table
    return new


def after_failure(split_horizon):
    """Stable tables of the line; then B - C fails, and the distances to C change."""
    line = {"A": {"B": 1}, "B": {"A": 1, "C": 1}, "C": {"B": 1}}
    tables = {r: {r: (0, r)} for r in line}
    for _ in range(3):
        tables = dv_round(line, tables, split_horizon)
    print("before:  A", tables["A"]["C"][0], " B", tables["B"]["C"][0])
    cut = {"A": {"B": 1}, "B": {"A": 1}, "C": {}}
    rounds = 0
    while True:
        new = dv_round(cut, tables, split_horizon)
        a, b = (new[r].get("C", (INFINITY,))[0] for r in "AB")
        if new == tables:
            return rounds
        tables, rounds = new, rounds + 1
        print(f"round {rounds:2}: A {a:2}  B {b:2}")


if __name__ == "__main__":
    print("both A and B unreachable after", after_failure(False), "rounds")
```

***Listing 32.4.** The line A – B – C, before and after the link B – C fails. code/grade-12/11-routing/listings/count_to_infinity.py*

```
$ python count_to_infinity.py
before:  A 2  B 1
round  1: A  2  B  3
round  2: A  4  B  3
round  3: A  4  B  5
round  4: A  6  B  5
round  5: A  6  B  7
round  6: A  8  B  7
round  7: A  8  B  9
round  8: A 10  B  9
round  9: A 10  B 11
round 10: A 12  B 11
round 11: A 12  B 13
round 12: A 14  B 13
round 13: A 14  B 15
round 14: A 16  B 15
round 15: A 16  B 16
both A and B unreachable after 15 rounds
```

***Output 32.3.** Each round, one of the two raises its distance by two, using the other’s old value.*

![Counting to infinity. After the failure each router takes the other’s distance, plus one, as its own; the values climb by two every two rounds until both reach 16, unreachable, at round 15.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-routing/fig-50f23fd0a130.svg)

*[Counting to infinity](#def-g12-routing-convergence). After the failure each router takes the other’s distance, plus one, as its own; the values climb by two every two rounds until both reach $16$, unreachable, at round $15$.*

The cure for this case is to stop A from telling B a route that goes through B. With *split horizon*, a router leaves out of the table it sends to a neighbour the routes whose [next hop](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table) is that neighbour. A variant, *poisoned reverse*, sends those routes with the distance $16$ instead.

```python
from count_to_infinity import after_failure

print("with split horizon: stable after", after_failure(True), "rounds")
```

***Listing 32.5.** The same failure, with split horizon. code/grade-12/11-routing/listings/split_horizon.py*

```
$ python split_horizon.py
before:  A 2  B 1
round  1: A  2  B 16
round  2: A 16  B 16
with split horizon: stable after 2 rounds
```

***Output 32.4.** B learns nothing about C any more, and marks it unreachable at once; A follows one round later.*

Split horizon prevents a loop of two routers. A loop of three or more can still count to infinity; the ceiling of $16$ is what finally ends it.

## 32.4 Link state

In [link-state routing](#def-g12-routing-routing-protocol), each router sends its own list of links, with their costs, to its neighbours. A router that receives a list it has not seen yet keeps a copy and passes it on to all its neighbours except the one it came from; a list it has already seen is dropped. This is *flooding*: every list reaches every router. Each router then holds the same map, and runs [Dijkstra’s algorithm](https://one-course.com/books/computer-science/2/en/chapter/26-graph-traversals-and-shortest-paths#met-g12-graph-algorithms-dijkstra) from itself; the first router on each shortest path is the [next hop](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table).

```python
"""Link-state routing: every router learns the whole map, then runs Dijkstra."""
from network import by_rate, graph


def flood(g):
    """Each router's list of links reaches every router; count the messages sent."""
    known = {r: {r} for r in g}                  # whose link lists r has received
    messages = 0
    for origin in g:
        queue = [(origin, None)]                 # (router that forwards, received from)
        while queue:
            r, came_from = queue.pop()
            for n in g[r]:
                if n == came_from:
                    continue                     # never sent back where it came from
                messages += 1
                if origin not in known[n]:
                    known[n].add(origin)         # new: keep it and pass it on
                    queue.append((n, r))
    return known, messages
```

***Listing 32.6.** Flooding the link lists: each router passes on the lists it has not seen yet. code/grade-12/11-routing/listings/link_state.py*

```python
def table(g, source):
    """Dijkstra from source; for each destination: (cost, first router on the way)."""
    tentative, best = {source: (0, source)}, {}
    while tentative:
        v = min(tentative, key=lambda r: (tentative[r], r))     # smallest cost
        d, first = best[v] = tentative.pop(v)                   # v is finished
        for w, cost in g[v].items():
            if w not in best and (w not in tentative or d + cost < tentative[w][0]):
                tentative[w] = (d + cost, w if v == source else first)
    return best


if __name__ == "__main__":
    g = graph(by_rate)
    known, messages = flood(g)
    print("every router knows all", len(g), "lists:", all(len(k) == len(g)
                                                         for k in known.values()))
    print("messages sent while flooding:", messages)
    for r in "AE":
        t = table(g, r)
        print(f"{r}'s table: " + "  ".join(f"{d}: {c} {n}" for d, (c, n) in
                                           sorted(t.items()) if d != r))
```

***Listing 32.7.** Dijkstra from each router, keeping the first router of each path. code/grade-12/11-routing/listings/link_state.py*

```
$ python link_state.py
every router knows all 7 lists: True
messages sent while flooding: 84
A's table: B: 10 B  C: 20 B  D: 110 B  E: 120 B  F: 120 B  G: 130 B
E's table: A: 120 D  B: 110 D  C: 120 D  D: 10 D  F: 20 D  G: 30 D
```

***Output 32.5.** The same distances as the distance vectors found, computed by each router on its own.*

Flooding one list costs one message on each link in each direction, except the links by which a router first heard the list: here $2 \times 9 - 6 = 12$ messages per list, $84$ for the seven. That is more traffic than one round of distance vectors, but it is sent only when a link changes.

![A’s shortest-path tree, with the cost of each link and A’s distance to each router. Every route from A leaves through B, which is why B is the next hop for every destination in A’s table. The dashed links are used by no shortest route from A.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-routing/fig-48eb2409200b.svg)

*A’s shortest-path tree, with the cost of each link and A’s distance to each router. Every route from A leaves through B, which is why B is the [next hop](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table) for every destination in A’s table. The dashed links are used by no shortest route from A.*

| **table of A** | **table of E** |
| --- | --- |
| destination | cost | [next hop](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table) | destination | cost | [next hop](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table) |
| B | 10 | B | A | 120 | D |
| C | 20 | B | B | 110 | D |
| D | 110 | B | C | 120 | D |
| E | 120 | B | D | 10 | D |
| F | 120 | B | F | 20 | D |
| G | 130 | B | G | 30 | D |

*Two [routing tables](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table) side by side, from the output above. A packet from A to G goes to B; B’s table sends it on to D, D’s to F, F’s to G. E sends even its packets for C through D, avoiding its own slow link to C.*

## 32.5 A link fails

The program below cuts the link D – F, then lets both methods find new routes. The distance vectors start from their stable tables of before; the link-state routers flood the change and run Dijkstra again.

```python
"""The link D - F fails: both methods find the new route from A to G."""
from dv_rounds import converge
from link_state import table
from network import by_rate, graph, route

g = graph(by_rate)
start = {r: {r: (0, r)} for r in g}
dv, _ = converge(g, start)                      # stable tables before the failure
print("before:     ", " ".join(route(dv, "A", "G")), " cost", dv["A"]["G"][0])

cut = graph(by_rate, down=[("D", "F")])
dv, rounds = converge(cut, dv, show="A")
print("distance vector:", rounds, "rounds;", " ".join(route(dv, "A", "G")),
      " cost", dv["A"]["G"][0])

ls = {r: table(cut, r) for r in cut}            # after flooding the change
print("link state:     ", " ".join(route(ls, "A", "G")), " cost", ls["A"]["G"][0])
```

***Listing 32.8.** The link D – F fails. code/grade-12/11-routing/listings/failure.py*

```
$ python failure.py
before:      A B D F G  cost 130
round  1  A knows  A:   0  B:  10  C:  20  D: 110  E: 120  F: 120  G: 130
round  2  A knows  A:   0  B:  10  C:  20  D: 110  E: 120  F: 120  G: 130
round  3  A knows  A:   0  B:  10  C:  20  D: 110  E: 120  F: 140  G: 150
round  4  A knows  A:   0  B:  10  C:  20  D: 110  E: 120  F: 140  G: 150
round  5  A knows  A:   0  B:  10  C:  20  D: 110  E: 120  F: 160  G: 170
round  6  A knows  A:   0  B:  10  C:  20  D: 110  E: 120  F: 160  G: 170
round  7  A knows  A:   0  B:  10  C:  20  D: 110  E: 120  F: 180  G: 190
round  8  A knows  A:   0  B:  10  C:  20  D: 110  E: 120  F: 180  G: 190
round  9  A knows  A:   0  B:  10  C:  20  D: 110  E: 120  F: 200  G: 210
round 10  A knows  A:   0  B:  10  C:  20  D: 110  E: 120  F: 200  G: 210
round 11  A knows  A:   0  B:  10  C:  20  D: 110  E: 120  F: 220  G: 220
round 12  A knows  A:   0  B:  10  C:  20  D: 110  E: 120  F: 220  G: 220
round 13  A knows  A:   0  B:  10  C:  20  D: 110  E: 120  F: 230  G: 220
distance vector: 13 rounds; A B D E G  cost 220
link state:      A B D E G  cost 220
```

***Output 32.6.** Both methods agree in the end, on a route of cost $220$ through E. The distance vectors need $13$ rounds, climbing $20$ at a time.*

The slow climb is [counting to infinity](#def-g12-routing-convergence) again, stopped this time by a real route. Right after the cut, D hears E say “F at $20$”, a route through D itself, and takes it: $30$, through E. E then hears $30$ from D, its [next hop](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table), and goes to $40$. For nine rounds D and E each name the other as the [next hop](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table) towards F, and a packet for F would bounce between them. Only when E’s figure passes $110$, the cost of its true route through G, does E switch to it; the news then needs a few more rounds to reach A.

The link-state routers do not count. Each one learns that the link is gone, removes it from its map, and computes the new tree in one go. The price is that every router stores the whole map and runs [Dijkstra’s algorithm](https://one-course.com/books/computer-science/2/en/chapter/26-graph-traversals-and-shortest-paths#met-g12-graph-algorithms-dijkstra), where a distance-vector router stores one line per destination and does additions. The hop-count protocol, with its ceiling of $15$ hops, was meant only for small networks.

## 32.6 Exercises

**Exercise 32.1 ★.**

Starting from tables that know only their own router, give D’s table after one round of distance vectors on the network of the chapter, with costs from rates.

**Solution of Exercise 32.1.**

D hears its three neighbours, each knowing only itself: B at cost $100$ through B, E at $10$ through E, F at $10$ through F, and itself at $0$.

**Exercise 32.2 ★.**

Find the route from A to G that has the fewest hops.

**Solution of Exercise 32.2.**

A – C – E – G, three hops. Every route through B needs at least four: A, B, D, then E or F, then G.

**Exercise 32.3 ★.**

Find the route from A to G of smallest cost, and its cost.

**Solution of Exercise 32.3.**

A – B – D – F – G, cost $10 + 100 + 10 + 10 = 130$. The fewest-hops [route costs](#def-g12-routing-metric) $100 + 1000 + 100 = 1200$.

**Exercise 32.4 ★.**

Using E’s table, and then the tables of the routers on the way, give the route of a packet from E to A.

**Solution of Exercise 32.4.**

E’s table gives D for A. D’s [next hop](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table) for A is B ($100 + 10$), and B’s is A. The route is E – D – B – A, of cost $10 + 100 + 10 = 120$, the cost in E’s table.

**Exercise 32.5 ★.**

Write `dv_update(table, neighbour, neighbour_table, cost)`, which returns a router’s table after it has heard one neighbour. Tables map each destination to a pair (distance, [next hop](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table)).

**Solution of Exercise 32.5.**

    `def dv_update(table, neighbour, neighbour_table, cost):`

        `new = dict(table)`

        `for dest, (d, _) in neighbour_table.items():`

            `if dest not in new or cost + d < new[dest][0]:`

                `new[dest] = (cost + d, neighbour)`

        `return new`

The copy leaves the old table unchanged, so that a round can use the old tables of all routers.

**Exercise 32.6 ★★.**

In `dv_round`, the comparison `<` is changed to `>`. What happens on the network of the chapter?

**Solution of Exercise 32.6.**

Each router keeps the *longest* sum it hears. A route may then go back and forth: A’s distance to E is $1100$ after two rounds, $3100$ after four, $5100$ after six, and keeps growing. The tables never become stable, and the distances describe no real shortest route. The tests run eight rounds and check that it still grows.

**Exercise 32.7 ★★.**

How many rounds does a line of $n$ routers need, starting from tables that know nothing, before its tables stop changing?

**Solution of Exercise 32.7.**

$n - 1$. News moves one link per round, and the farthest pair, the two ends, are $n - 1$ links apart; after round $n - 1$ every router knows every destination by its only route, and one more round changes nothing.

**Exercise 32.8 ★★.**

Write `cost_from_rate(rate, ref)`. What should it return for a link faster than the reference, and why?

**Solution of Exercise 32.8.**

    `def cost_from_rate(rate, ref):`

        `return max(1, ref // rate)`

A link faster than the reference would get $0$ from the integer division. A cost of $0$ would make a chain of such links as cheap as one of them, so routes could wander through many routers for free; the least cost is $1$. The price is that links faster than the reference all look the same, so the reference is chosen above the fastest link of the network.

**Exercise 32.9 ★★.**

The link B – D fails instead of D – F. What is the new route from A to G, and its cost?

**Solution of Exercise 32.9.**

A – B – C – E – D – F – G, cost $10 + 10 + 1000 + 10 + 10 + 10 = 1050$. B – D was the only fast way from the left half to the right; the slow link C – E, at $1000$, is now on every route. A – C – E costs $1100$, more than A – B – C – E at $1020$.

**Exercise 32.10 ★★.**

A cable can fail in one direction only: D still receives from E, but E no longer receives from D. D keeps listing the link D – E; E removes it. A link-state router builds its map from every list it receives, keeping a link when either end lists it. What goes wrong, and what is the fix?

**Solution of Exercise 32.10.**

Every router keeps D – E in its map, since D lists it. Routes that use the link from E to D are then computed as if it worked, and packets sent that way are lost. The fix: keep a link in the map only when *both* its ends list it, which means each end has checked that it receives from the other.

**Exercise 32.11 ★★.**

How many messages does flooding all the link lists send on a ring of $n$ routers?

**Solution of Exercise 32.11.**

For one list, the origin sends on its $2$ links, and each of the $n - 1$ other routers, on first receiving the list, sends it on its $2$ links except the one it came from: $2 + (n - 1) = n + 1$ messages. For the $n$ lists: $n(n + 1)$. In general, $2e - (n - 1)$ per list for $e$ links.

**Exercise 32.12 ★★★.**

Prove that after $k$ rounds of `dv_round`, starting from tables that know only their own router, each router’s distance to each destination is the smallest cost of a route of at most $k$ links, and that destinations with no such route are absent.

**Solution of Exercise 32.12.**

By induction on $k$. For $k = 0$, each router knows only itself at $0$: the only route of $0$ links. Suppose it true after round $k$. In round $k + 1$, router $r$ takes for each destination $d$ the smallest $c + x$ over its neighbours $n$, where $c$ is the cost of the link to $n$ and $x$ the smallest cost from $n$ to $d$ with at most $k$ links. A route from $r$ to $d$ of at most $k + 1$ links is either the empty route ($d = r$, kept at $0$), or a first link to some $n$ followed by a route of at most $k$ links from $n$: its cost is at least $c + x$ for that $n$. And each $c + x$ is the cost of such a route. So the minimum is the smallest cost with at most $k + 1$ links, and a destination is absent exactly when no neighbour knows it, that is, when no such route exists. The tests compare the two on $50$ random [graphs](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph).

**Exercise 32.13 ★★★.**

In the count of the chapter, A starts at $2$ and B at $1$. Show that both reach the ceiling $M$ after $M - 1$ rounds. How many rounds would a ceiling of $64$ take? If each round took the $30$ seconds between two periodic updates of the hop-count protocol, how long would the count of the chapter last?

**Solution of Exercise 32.13.**

After round $k$, the router updated in that round holds $k + 2$ and the other $k + 1$ (round $1$: B $3$, A $2$). Both have reached $M$ when the smaller does: $k + 1 = M$, so $k = M - 1$. For $M = 16$, $15$ rounds, as printed; for $M = 64$, $63$. At $30$ seconds a round, $15$ rounds last $450$ seconds, seven and a half minutes, during which packets for C bounce between A and B.

**Exercise 32.14 ★★★.**

Change `dv_round` to use poisoned reverse, and count the rounds after the failure on the line of three routers, and on a line of four, R1 – R2 – R3 – R4, when R3 – R4 fails.

**Solution of Exercise 32.14.**

In the loop over a neighbour’s table, a route whose [next hop](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table) is the router receiving it is counted at $16$:

    `if poison and via == r:`

        `d = INFINITY`

On the line of three, $2$ rounds, as with split horizon: B hears “C at $16$” from A at once. On the line of four, $3$ rounds: R3 knows at once, R2 one round later, R1 one more. The tests check both counts.

**Exercise 32.15 ★★★.**

Explain why the ceiling of $16$ limits the networks that the hop-count protocol can serve to routes of at most $15$ hops, and why its designers did not choose a much larger ceiling.

**Solution of Exercise 32.15.**

A distance of $16$ means unreachable, so a destination $16$ hops away cannot be told apart from one that does not exist: every route used must have at most $15$ hops, which bounds the diameter of the network. A larger ceiling would serve larger networks, but every count to infinity would last longer, about one round per unit of the ceiling (exercise [32.13](#exo-g12-routing-13)). The designers kept it small so that counts end quickly, and meant the protocol for small networks.

## 32.7 Problem: Counting to Infinity

**Problem 32.1.**

Weekend problem — how long does bad news take?

This problem follows the line A – B – C of section [32.3](#sec-32-3), with [hop counts](#def-g12-routing-metric), through a failure, with and without split horizon, then with link state. The outputs [32.3](#out-g12-routing-infinity) and [32.4](#out-g12-routing-split) give the rounds.

**Part I — The line.**

1. Write the table of each router (destination, distance, [next hop](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table) ) once the protocol has [converged](#def-g12-routing-convergence) .
2. How many rounds does it take to converge from tables that know nothing?
3. Why does A need B to know anything about C?
4. In round $1$ after the failure, B hears “C at $2$ ” from A. What does that $2$ really describe?

**Part II — Without split horizon.**

5. Explain the first round after the failure: why does B go to $3$ , while A stays at $2$ ?
6. Explain the second round: why does A go to $4$ , although $4$ is larger than its old $2$ ?
7. During the count, where does a packet from A to C go?
8. Why do the values climb by two every two rounds?
9. At which round do both reach $16$ ? Check it against the output.
10. With updates every $30$ seconds, how long does the count last?

**Part III — With split horizon.**

11. Which line of its table does A leave out when it writes to B? Why?
12. Why does B mark C unreachable in round $1$ ?
13. Why does A need a second round?
14. Add a router D linked to both A and B, giving a triangle A – B – D with C hanging from B. Describe how B can still learn a false route to C through D after the failure.
15. Does poisoned reverse change the answer of the line? Of the triangle?

**Part IV — With link state.**

16. After the failure, which routers send a new list, and what does it say?
17. How many messages does the flooding of those lists take on the line?
18. Why can a link-state router not count to infinity?
19. What does a link-state router pay for that, in memory and in work?
20. State the result: how many rounds does each method need before A and B know that C is unreachable?

**Solution of Problem 32.1.**

**1.** A: B at $1$ through B, C at $2$ through B. B: A at $1$ through A, C at $1$ through C. C: B at $1$ through B, A at $2$ through B.

**2.** Two rounds: in the first, each router learns its neighbours; in the second, A and C learn each other through B (exercise [32.7](#exo-g12-routing-7) with $n = 3$).

**3.** B is A’s only neighbour; A hears about the rest of the network only from B.

**4.** A’s route to C goes through B: that $2$ is B’s own old link to C, plus one. It is out of date, but B cannot tell.

**5.** Each round uses the tables of the previous round. B’s only neighbour is now A, whose old table says $2$: B takes $3$. A still reads B’s old table, which said $1$: A stays at $2$.

**6.** A rebuilds its table from what its neighbours say now. B, its only neighbour and its [next hop](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table), now says $3$, so A’s best is $4$: it cannot keep $2$, since nothing supports it any more.

**7.** A sends it to B, and B, whose [next hop](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table) for C is A, sends it back: the packet bounces between them until it is dropped.

**8.** Each router copies the other’s previous value plus one; the values alternate, so each one rises by two every two rounds, and in each round only one of them changes.

**9.** At round $15$: A reaches $16$ in round $14$, B in round $15$, as printed.

**10.** $15 \times 30 = 450$ seconds, seven and a half minutes.

**11.** Its route to C, whose [next hop](https://one-course.com/books/computer-science/2/en/chapter/15-network-layers-and-protocols#def-g11-network-protocols-routing-table) is B. Telling B “I reach C” would describe B’s own route.

**12.** B has no link to C any more, and its only neighbour tells it nothing about C, so B has no route at all.

**13.** In round $1$, A still reads B’s table of before the failure, with C at $1$. Only in round $2$ does it read B’s new table, without C.

**14.** After the failure, A and D both still reach C through B, so neither tells B. But A tells D, and D tells A, since each one’s route goes through B, not through the other. In round $1$ B has no route; in round $2$ A takes D’s “C at $2$” as $3$ through D, and in round $3$ B takes A’s $3$ as $4$ through A. The false route goes around the triangle, one router at a time, gaining one hop per round, and the smallest distance reaches $16$ only at round $15$. The tests run this case.

**15.** On the line, no: B already hears nothing, and with poison it hears $16$, which means the same. In the triangle, no: the loop passes through three routers, and each tells the next a route that goes through a third one, which neither split horizon nor poisoned reverse forbids.

**16.** B, which sends a list with its one remaining link, to A. C has no link left, so it cannot send anything, and nobody needs to hear from it.

**17.** One: from B to A. A has no other neighbour to pass it on to.

**18.** It never learns distances from other routers. It computes them from its map, in which C is no longer connected to anything: [Dijkstra’s algorithm](https://one-course.com/books/computer-science/2/en/chapter/26-graph-traversals-and-shortest-paths#met-g12-graph-algorithms-dijkstra) does not reach C, so C is unreachable as soon as the map is updated.

**19.** Memory for the whole map, and a run of [Dijkstra’s algorithm](https://one-course.com/books/computer-science/2/en/chapter/26-graph-traversals-and-shortest-paths#met-g12-graph-algorithms-dijkstra) at every change, against one line per destination and some additions for distance vectors; plus the flooding at every change.

**20.** **On the line A – B – C, after the link B – C fails, distance vectors count to infinity: $15$ rounds pass before A and B both mark C unreachable, seven and a half minutes at $30$ seconds a round. With split horizon, B knows at round $1$ and A at round $2$; with link state, a single message from B to A is enough.**
