কম্পিউটার বিজ্ঞান · বই 4 · স্নাতক দ্বিতীয় বর্ষ

University Computer Science — Year 2

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

University Computer Science — Year 2 · স্নাতক দ্বিতীয় বর্ষ

18The Network Layer: IP and Routing

A packet leaves the laptop at the library for a server at the far end of town. Each router on the way takes one off a counter in the packet, and the router that brings it to zero sends back a note. Sending packets with counters 1, 2, 3, … therefore reveals the path, one router 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 at each place of the town).

Nine routers, then the server: the laptop knew none of them, and each router chose the next one on its own. The link layer of Chapter 17 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 chooses where a packet goes next, and how routers 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 table, read by hand, tells a router where to send a packet, and routers 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: the Internet 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.11001011\;00000000\;01110001\;01001101 .

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

Definition 18.1 (Prefix)

A prefix a/pa/p, with 0≤p≤320 \le p \le 32, is the set of addresses whose first pp bits are those of aa. Its mask is the 32-bit number made of pp ones then 32−p32 - p zeros. An address xx belongs to a/pa/p exactly when x&mask=a&maskx \mathbin{\&} \text{mask} = a \mathbin{\&} \text{mask}; that common value is the network address, and the address with the 32−p32 - 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.
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.
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, each checked against Python’s ipaddress.

Method 18.2 (Subnet arithmetic)

A prefix /p/p holds 232−p2^{32-p} addresses, of which 232−p−22^{32-p} - 2 can name machines (the network and broadcast addresses are kept). To split a/pa/p into 2k2^k equal subnets, extend the prefix by kk bits: the subnets are a+i⋅232−p−ka + i \cdot 2^{32-p-k} over /(p+k)/(p + k), for i=0,…,2k−1i = 0, \dots, 2^k - 1. To find the smallest prefix for hh machines, take the least ss with 2s−2≥h2^s - 2 \ge h: the prefix is /(32−s)/(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).

History

2322^{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 2242^{24} addresses, one to each regional registry, and had none left. Address translation (Section 18.3) and IPv6 (Section 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).

Definition 18.4 (Forwarding table, longest-prefix match)

A forwarding table is a list of prefixes, each with a next hop. A packet for address xx goes to the next hop of the longest prefix of the table that contains xx (longest-prefix match). The prefix 0.0.0.0/0, which contains every address, is the default route.

The longest 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 costs one test per entry, and backbone routers 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 of length pp marks the node reached by its pp bits.

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 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.
The trie of the table ∗→0\ast \to 0, 01∗→301\ast \to 3, 1∗→11\ast \to 1, 101∗→2101\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 of the table that contains the address, after at most 32 steps.

Proof. After kk steps the walk is at the node of the address’s first kk bits. The node of a prefix a/pa/p lies on this path exactly when the first pp bits of the address are those of aa, that is, when the prefix contains the address. The walk passes the marked nodes of all these prefixes 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.
$ 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 use compressed tries, and special memories that compare an address with every 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).
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.

Definition 18.6 (Time to live)

The time to live of a packet is a counter in its header that every router decreases by one; a router that brings it to zero destroys the packet, so that a packet caught in a routing loop cannot circle forever, and sends back a “time exceeded” message.

That message is what Output 18.1 used. The header checksum, the Internet checksum of Chapter 17 computed over the header with the field taken as 0, must then be computed again.

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 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 dropped from 64 (0x40) to 63, and the checksum 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 translates.

Definition 18.7 (Network address and port translation)

A NAT router 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.

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.
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.

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 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 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 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 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: they send with “don’t fragment” set and lower their packet size when a router 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.

21282^{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), and the two addresses. There is no header checksum, since the link and transport layers each have their own, and routers 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 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 are filled by routing protocols. Inside one network, routers use one of two families, both computing shortest paths in the graph of routers 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 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 sends its table of distances to its neighbours, and rebuilds its own table from theirs: the distance to dd is the least, over neighbours vv, of the link cost to vv plus vv’s distance to dd, and the next hop is that vv. This is the Bellman–Ford algorithm, run by all the routers together.

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, 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 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 nn routers and positive link costs, and let every table start with only the router itself, at distance 0. After round kk of synchronous distance vector, each router’s distance to each destination is the least cost of a path to it with at most kk links. Hence after n−1n - 1 rounds every distance is the shortest-path distance, and no table changes after that.

The proof, by induction on kk, is Exercise 18.8. On the town’s 30 routers the tables stop changing after 8 rounds, the most links on any shortest path, and agree with Dijkstra’s algorithm run at each router:

$ 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 cc the link cost, ar=br−1+ca_{r} = b_{r-1} + c and br=ar−1+cb_r = a_{r-1} + c (capped at infinity). Hence max⁡(ar,br)=max⁡(ar−1,br−1)+c\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.
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 tell the neighbour it routes through that its distance is infinite; it cures this two-router loop, but not every loop (Exercise 18.10).

18.6.2 Link state

Definition 18.13 (Link-state routing)

In link-state routing, each router floods to every other router a description of its own links, so that every router 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 at its ends flood the news, and every router computes again, once. OSPF, the common link-state protocol, works this way. The cost is that every router stores the whole map and runs Dijkstra on each change; the gain is fast, loop-free convergence.

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’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 under one technical administration, which uses its own routing protocol inside. In path-vector routing, each announcement of a 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 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.
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

Solution of Exercise 18.1.

198.51.100.77/27: mask 255.255.255.224; 77=64+1377 = 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=3032 - 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 does it really compute, and is the answer to the membership test right?

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

Solution of Exercise 18.2.

The shift is by 32−p+132 - p + 1 instead of 32−p32 - p, so the mask has p−1p - 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 start alike. Testing against ipaddress, as cidr.py does, catches it on the first address.

Exercise 18.3 ★

Write contains(prefix, address) for prefixes and addresses in text, using cidr.py.

Solution

Solution of Exercise 18.3.

def contains(prefix, address):
    net, length = parse(prefix)
    addr, _ = parse(address)
    return addr & mask(length) == net & mask(length)
Membership in a prefix code/bachelor-2/18-network-layer/exercises/contains.py

Masking both sides makes the function correct even for a 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 for four offices of 50, 20, 10 and 2 machines, without overlap.

Solution

Solution of Exercise 18.4.

A /26 holds 26−2=622^6 - 2 = 62 machines. The offices need ss with 2s−22^s - 2 at least 50, 20, 10 and 2: s=6,5,4,2s = 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 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

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 is lowered, this router computes the checksum without first clearing the field. What does the next router see, and how does the error show in the output?

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 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

Solution of Exercise 18.6.

The new checksum is the complement of a sum that includes the old checksum, so it is not the complement of the sum of the other words. The next router 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 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 with the same next hop by the fewest prefixes covering exactly the same addresses: drop a prefix inside another, merge two halves of a prefix. Test it against ipaddress.collapse_addresses.

Solution

Solution of Exercise 18.7.

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 code/bachelor-2/18-network-layer/exercises/aggregate.py

Two rules are applied until neither applies: a prefix inside a shorter one of the set is dropped; two prefixes of the same length that differ only in their last bit, the two halves of a prefix one bit shorter, are replaced by it. The result covers the same addresses, and it is the fewest prefixes: in the final set no 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.

Solution

Solution of Exercise 18.8.

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

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

With positive costs a shortest path visits no router twice, so it has at most n−1n - 1 links: Dn−1(u,d)D_{n-1}(u, d) is the shortest distance, and Dk=Dn−1D_k = D_{n-1} for every k≥n−1k \ge n - 1. The distances therefore stop changing after at most n−1n - 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, and give by hand the fragments of 3000 bytes for an MTU of 1006. Why must every fragment but the last carry a multiple of 8 bytes?

Solution

Solution of Exercise 18.9.

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 code/bachelor-2/18-network-layer/listings/fragment.py

With an MTU of 1006, each fragment carries at most (1006−20)(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 (213−1)×8=65 528(2^{13} - 1) \times 8 = 65\,528 bytes cover any packet, whose total length is at most 65 53565\,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

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 vv’s route to dd goes through uu, uu 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 from echoing a route back to its own next hop, a loop of two; this loop has three, and the routers 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, which must also handle nested prefixes. Relate your estimates to Output 18.4.

Solution

Solution of Exercise 18.11.

A linear table costs one test per prefix: nn tests, as the printed times show (about 0.9 µs per prefix, four times the time for four times the prefixes). A trie costs one step per bit of the longest matching path, at most 32, whatever nn; its time rises a little with nn only because more prefixes make longer paths. Binary search does not work directly on nested prefixes, since the longest match need not be next to the address in sorted order. Each prefix is a range of addresses; the nn ranges cut the address space into at most 2n+12n + 1 intervals, each labelled with the longest prefix that contains it. A binary search among these intervals costs log⁡2(2n+1)\log_2(2n + 1) steps, about 13 for 4000 prefixes, 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 from its eight groups, and test it against ipaddress on many addresses with runs of zeros.

Solution

Solution of Exercise 18.12.

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 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 gets one address, 198.51.100.kk for place kk. 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 for one, and how many such prefixes fit in a /24?
  3. Could the 30 small networks all fit in 198.51.100.0/24 besides the routers’ addresses? Justify.
  4. The town gets a second block, 203.0.113.0/24, and gives place kk the /29 that starts at 203.0.113.8k8k. Check that the 30 prefixes fit, and give the prefix of place 12.
  5. Write the network and broadcast addresses of that prefix.
  6. Why does this plan make forwarding tables easy to read?

Part II — Forwarding tables.

  1. In Output 18.1, which router forwards the packet to the Town Square router?
  2. How many entries does a router’s table need with one /29 per place, and how many if the town announces itself to the outside as one prefix?
  3. Write the two entries a router at the edge of town needs for the outside world.
  4. A packet for 203.0.113.97 arrives. Which place’s network is it in?
  5. Count the steps of a trie lookup for that address in a table of the 30 /29s and a default route.
  6. Why is the time to live set to 64 rather than to the 9 hops the hook needed?

Part III — Distance vector against link state.

  1. With road lengths as costs, distance vector stops changing after 8 rounds. What does Theorem 18.11 say the number of rounds is at most, and what does 8 measure?
  2. With hop counts as costs, it takes 7 rounds. Why fewer?
  3. How many messages does one round of distance vector send in the town’s network?
  4. How many link descriptions does each router store in link state?
  5. Estimate the work of one Dijkstra run on 30 routers and 53 links.
  6. Which design would you choose for the town, and why?

Part IV — A router fails.

  1. The router 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.
  2. Explain the first three lines: why does the nearest router’s distance go 1, 2, 3, 4?
  3. Why does it take 15 rounds, whatever the router’s distance before?
  4. With RIP’s 30 seconds per round, how long is the café’s network wrongly announced as reachable?
  5. What does link state do instead, and how long does it take?
  6. State the result: count to infinity, 15 rounds to reach the limit 16, against one recomputation in link state.
Solution

Solution of Problem 18.1.

1. 256−30=226256 - 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 229−24=322^{29-24} = 32 of them.

3. No. The router addresses 1 to 30 fall in the first four /29s (0 to 31), which leaves 28 for 30 networks.

4. Place kk gets 8k8k to 8k+78k + 7; for k=30k = 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, 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.

9. 203.0.113.0/24 (and the routers’ 198.51.100.0/24) towards the inside, and 0.0.0.0/0 towards the provider.

10. 97=8×12+197 = 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 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=29n - 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 sends its table to each neighbour: 2×53=1062 \times 53 = 106 messages per round.

16. The whole map: the 53 links (each described by both of its routers, 106 descriptions).

17. With a heap, about (n+m)log⁡2n≈(30+106)×5≈700(n + m)\log_2 n \approx (30 + 106) \times 5 \approx 700 elementary steps: nothing for a router.

18. Link state: the map is small, each router 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 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 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 that believes in an older, shorter one.

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

22. 15×3015 \times 30 s, seven and a half minutes, during which packets for the café circle until their time to live runs out.

23. The café’s neighbours flood the loss of their links; each router 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 in link state.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো