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

# Chapter 17 — The Link Layer

The town’s lighthouse is told by radio when to light its lamp. One evening a [burst](#def-b2-link-layer-burst) of noise flips a single bit of the message on its way:

```
$ python lighthouse.py
sent:      LAMP ON AT 20:00   check 788582f7
received:  LAMP ON AT 21:00   check 788582f7
recomputed check of what arrived: c039e592
frame dropped
```

***Output 17.1.** One flipped bit, and who notices it.*

“20:00” became “21:00”: the character `0` is the byte `0x30` and `1` is `0x31`, one bit apart. The message still reads well, so no person would notice. The receiver noticed because the sender had added four bytes computed from the message, a *check*, and the received message no longer matches it. This chapter is about the bottom of the network: how a stream of bits on one wire or one radio channel is cut into [frames](#def-b2-link-layer-frame), how errors are detected, how many machines share one medium, and how a [frame](#def-b2-link-layer-frame) finds its way across a local network.

**You already know.**

Book 2: the network is built in layers, each using the one below; a protocol is a set of rules that both sides follow. The physics series: a signal on a wire or in the air weakens with distance and picks up noise. [Chapter 16](https://one-course.com/books/computer-science/4/en/chapter/16-sockets#ch-b2-sockets): bytes sent over a [socket](https://one-course.com/books/computer-science/4/en/chapter/16-sockets#def-b2-sockets-socket) arrive intact and in order; this chapter and the next two show who makes that true.

## 17.1 Links and frames

**Definition 17.1 (Link, frame).**

A *link* connects machines that can reach each other directly: a cable between two machines, or a radio channel that all of them hear. The *link layer* carries *frames*: a frame is a block of bytes with a header (who sends it, to whom, what it carries), a payload, and a check. The link layer hands frames to the layer above; a frame never leaves its link.

The first problem is to find where a [frame](#def-b2-link-layer-frame) begins and ends in a stream of bits. A common answer marks the ends with a special byte, the *flag*. A flag byte inside the payload must then be disguised.

**Method 17.2 (Byte stuffing).**

[Frames](#def-b2-link-layer-frame) begin and end with the flag `0x7e`. Inside a [frame](#def-b2-link-layer-frame), the sender replaces each byte `0x7e` or `0x7d` by the escape `0x7d` followed by the byte XOR `0x20`. The receiver cuts the stream at the flags, and in each [frame](#def-b2-link-layer-frame) replaces `0x7d`, $b$ by $b$ XOR `0x20`.

```python
def stuff(payload):
    out = bytearray([FLAG])
    for b in payload:
        if b in (FLAG, ESC):
            out += bytes([ESC, b ^ 0x20])     # never a flag inside the frame
        else:
            out.append(b)
    out.append(FLAG)
    return bytes(out)


def unstuff(frame):
    assert frame[0] == FLAG and frame[-1] == FLAG
    out, escaped = bytearray(), False
    for b in frame[1:-1]:
        if escaped:
            out.append(b ^ 0x20)
            escaped = False
        elif b == ESC:
            escaped = True
        else:
            out.append(b)
    return bytes(out)
```

***Listing 17.1.** Stuffing and unstuffing code/bachelor-2/17-link-layer/listings/stuffing.py*

```
$ python stuffing.py
payload: 41 7e 42 7d 43
on the wire: 7e 41 7d 5e 42 7d 5d 43 7e 7e 4f 4b 7e
frames found: ['41 7e 42 7d 43', '4f 4b']
```

***Output 17.2.** Two [frames](#def-b2-link-layer-frame) on the wire.*

After stuffing, `0x7e` occurs only at the ends of a [frame](#def-b2-link-layer-frame), so the cut at the flags is exact. XOR with `0x20` is its own inverse, which is why the receiver applies the same operation.

## 17.2 Detecting errors

Noise flips bits.

**Definition 17.3 (Error-detecting code, checksum).**

An *error-detecting code* adds to each block of data a few check bits computed from it; the receiver computes them again from what arrived, and drops the block if they differ. A *checksum* is a check computed by adding the data as numbers; a [parity bit](#def-b2-link-layer-parity), below, is the smallest check.

No check catches every error: the question is which errors each one is sure to catch.

### 17.2.1 Parity

**Definition 17.4 (Parity bit).**

The *even parity bit* of a block of bits is 1 if the block has an odd number of 1s, and 0 otherwise, so that the block and its parity bit together hold an even number of 1s.

**Proposition 17.5 (Parity).**

A [parity bit](#def-b2-link-layer-parity) detects every error that flips an odd number of bits of the block and its [parity bit](#def-b2-link-layer-parity), and no error that flips an even number.

**Proof.** Sent, the block and its bit hold an even number of 1s. Each flip changes that number by $\pm 1$, so after $k$ flips it has changed by $k$ modulo 2: it is odd, and the receiver sees the error, exactly when $k$ is odd. ∎

```
$ python parity.py
bytes: 4c 41 4d 50  parity bits: [1, 0, 0, 0]
one flip in byte 2:  [1, 0, 1, 0] -> byte 2 fails
two flips in byte 2: [1, 0, 0, 0] -> nothing seen
grid: row 2 and column 3 disagree: flip bit 3 of byte 2
corrected: True
```

***Output 17.3.** One [parity bit](#def-b2-link-layer-parity) per byte, then a grid of parities.*

Arranged as a grid, with a [parity bit](#def-b2-link-layer-parity) per row (byte) and a parity byte for the columns, parity does more: a single flip makes exactly one row and one column wrong, and their crossing is the bit to flip back. The code *corrects* the error ([Exercise 17.3](#exo-b2-link-layer-3)). The price is one bit in nine, plus a byte per block.

### 17.2.2 The Internet checksum

The Internet’s own protocols use a cheaper check.

**Definition 17.6 (Internet checksum).**

The *Internet checksum* adds the data as 16-bit words, adding each carry out of the top back in at the bottom (the *one’s complement sum*), and sends the complement of the result. The receiver adds everything, [checksum](#def-b2-link-layer-edc) included, and expects `ffff`.

```python
def ones_sum(data):
    if len(data) % 2:
        data += b"\0"
    total = 0
    for i in range(0, len(data), 2):
        total += data[i] << 8 | data[i + 1]
        total = (total & 0xFFFF) + (total >> 16)   # add the carry back at the bottom
    return total


def checksum(data):
    return ~ones_sum(data) & 0xFFFF
```

***Listing 17.2.** The one’s complement sum and the [checksum](#def-b2-link-layer-edc) code/bachelor-2/17-link-layer/listings/inet_checksum.py*

```
$ python inet_checksum.py
checksum: 360e
receiver's sum with it: ffff
two words swapped:      ffff
one bit flipped:        0100
```

***Output 17.4.** It catches a flipped bit, not two swapped words.*

A sum does not depend on the order of its terms, so swapping two words passes unseen. The [checksum](#def-b2-link-layer-edc) is fast to compute in software, which is why the Internet layers use it; the [links](#def-b2-link-layer-frame), which see the noise, use a stronger check.

### 17.2.3 Cyclic redundancy codes

A [cyclic redundancy code](#def-b2-link-layer-crc) treats a string of bits as a polynomial whose coefficients are 0 or 1: the bits $1101$ are $x^3 + x^2 + 1$. Coefficients are added modulo 2, so adding is XOR, with no carries, and $x^k + x^k = 0$. Polynomials can be multiplied and divided with remainder exactly as with numbers, the subtractions in a long division being XORs.

**Definition 17.7 (Cyclic redundancy code).**

Let $g(x)$ be a polynomial of degree $r$ whose constant term is 1, the *generator*. A message $M(x)$ is sent as $T(x) = M(x)\,x^r + R(x)$, where $R(x)$ is the remainder of $M(x)\,x^r$ divided by $g(x)$: the message followed by $r$ *check bits*. The receiver accepts a [frame](#def-b2-link-layer-frame) $T'(x)$ if $g(x)$ divides it. This is a *cyclic redundancy code*, or CRC.

Since $M x^r = Q g + R$ and $R + R = 0$, $T = M x^r + R = Q g$: every [frame](#def-b2-link-layer-frame) sent is a multiple of $g$. The long division is mechanical:

```
$ python long_division.py
  11010110110000   message followed by 4 zeros
  10011   XOR g
  --------------
  01001110110000
   10011   XOR g
  --------------
  00000010110000
        10011   XOR g
  --------------
  00000000101000
          10011   XOR g
  --------------
  00000000001110
remainder: 1110; the frame sent: 1101011011 1110
```

***Output 17.5.** A CRC by long division, with $g(x) = x^4 + x +
1$: XOR $g$ under every leading 1.*

```python
def remainder(message, n, g):
    """Remainder of message(x) * x^r divided by g(x): message has n bits, g degree r."""
    r = g.bit_length() - 1
    value = message << r
    for i in range(n + r - 1, r - 1, -1):     # from the top bit down to bit r
        if value >> i & 1:
            value ^= g << (i - r)             # subtract g, written under bit i
    return value
```

***Listing 17.3.** The same division in code, on the bits of an integer code/bachelor-2/17-link-layer/listings/crc.py*

If the noise adds an error $E(x)$ (a 1 at each flipped bit), the receiver gets $T + E$, and since $g$ divides $T$, it accepts exactly when $g$ divides $E$. So the errors a CRC misses are the multiples of its generator, and choosing a CRC is choosing $g$.

**Definition 17.8 (Burst error).**

A *burst* of length $b$ is an error whose first and last flipped bits are $b$ positions apart, counting both; the bits between them may be flipped or not.

**Theorem 17.9 (Bursts).**

A CRC whose generator has degree $r$ and constant term 1 detects every [burst](#def-b2-link-layer-burst) of length $b \le r$.

**Proof.** Such an error is $E(x) = x^i B(x)$, where $B$ has degree $b - 1 < r$ and constant term 1. First, if $g$ divides $x
C(x)$ for some $C$, then $g$ divides $C$: write $xC = gQ$; the constant term of $gQ$ is that of $Q$, because $g$’s is 1, and it is 0, because $xC$ has none; so $Q = xQ'$, and $xC = x\,gQ'$ gives $C = gQ'$. Applying this $i$ times, if $g$ divided $E$ it would divide $B$. But a nonzero multiple of $g$ has degree at least $r$, and $B$ is nonzero of degree less than $r$. So $g$ does not divide $E$. ∎

**Proposition 17.10 (Odd numbers of flips).**

If $x + 1$ divides the generator, the CRC detects every error with an odd number of flipped bits.

The proof is [Exercise 17.8](#exo-b2-link-layer-8); the idea is to evaluate polynomials at $x = 1$. The 16-bit generator

$x^{16} + x^{12} + x^5 + 1$ has four terms, so it is divisible by $x + 1$, and both results apply. They can be checked by brute force on a [frame](#def-b2-link-layer-frame) of 4 bytes and its 16 check bits:

```
$ python burst_check.py
frame of 48 bits; burst length, bursts tried, bursts undetected
  1        48     0
  2        47     0
  8      2624     0
 15    278528     0
 16    540672     0
 17   1048576    32
all bursts of 1 to 16 bits: 1114111 tried, 0 undetected
```

***Output 17.6.** Every [burst](#def-b2-link-layer-burst) of up to 17 bits through CRC-16.*

Not one [burst](#def-b2-link-layer-burst) of 16 bits or fewer passes. Of the [bursts](#def-b2-link-layer-burst) of 17 bits, exactly one pattern per position passes: the generator itself, shifted.

### 17.2.4 CRC-32 in practice

The 32-bit CRC of Ethernet uses a generator of degree 32 written `0x104c11db7` as a bit vector. Real CRCs add two details to the definition. The hardware sends each byte lowest bit first, so the bits are processed in that order, and the generator appears reversed, as `0xedb88320`. The register starts at all ones, so that leading zero bytes

change the check, and the result is complemented. The same CRC-32 protects zip and gzip files and PNG images:

```python
def crc32_bitwise(data):
    """CRC-32 of zlib: bits taken lowest first, so the generator is reversed."""
    crc = 0xFFFFFFFF
    for byte in data:
        crc ^= byte
        for _ in range(8):
            crc = (crc >> 1) ^ 0xEDB88320 if crc & 1 else crc >> 1
    return crc ^ 0xFFFFFFFF


def _step8(b):
    for _ in range(8):
        b = (b >> 1) ^ 0xEDB88320 if b & 1 else b >> 1
    return b


TABLE = [_step8(b) for b in range(256)]      # the eight steps of each byte value


def crc32_table(data):
    crc = 0xFFFFFFFF
    for byte in data:
        crc = TABLE[(crc ^ byte) & 0xFF] ^ (crc >> 8)
    return crc ^ 0xFFFFFFFF
```

***Listing 17.4.** CRC-32 bit by bit, then a byte at a time from a table code/bachelor-2/17-link-layer/listings/crc.py*

```
$ python crc.py
0x04c11db7 reversed: 0xedb88320
input               bitwise    table     zlib
''                 00000000 00000000 00000000
'a'                e8b7be43 e8b7be43 e8b7be43
'123456789'        cbf43926 cbf43926 cbf43926
'LAMP ON AT 20:00' 788582f7 788582f7 788582f7
'1024 bytes'       b70b4c26 b70b4c26 b70b4c26
crc16(LAMP) = 2a56, by division: 2a56
```

***Output 17.7.** Three ways, one value: ours agrees with `zlib.crc32`.*

The table holds, for each byte value, the effect of eight steps of the bitwise loop; one lookup replaces eight steps. The same table in C gives the same values:

```c
uint32_t crc32(const unsigned char *data, size_t n)
{
    uint32_t crc = 0xFFFFFFFFu;
    for (size_t i = 0; i < n; i++)
        crc = table[(crc ^ data[i]) & 0xFF] ^ (crc >> 8);
    return crc ^ 0xFFFFFFFFu;
}
```

***Listing 17.5.** The table-driven CRC-32 in C code/bachelor-2/17-link-layer/listings/crc32.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o crc32 crc32.c -lm && ./crc32
00000000  ""
e8b7be43  "a"
cbf43926  "123456789"
788582f7  "LAMP ON AT 20:00"
```

***Output 17.8.** The values of the C program.*

## 17.3 Sharing a medium

On a radio channel, every station hears every other.

**Definition 17.11 (Multiple access protocol, collision).**

When several stations share one medium and two transmit at once, their signals mix and both [frames](#def-b2-link-layer-frame) are lost: a *collision*. A *multiple access protocol* (or medium access protocol) is the rule by which each station decides when to transmit.

**History.**

In 1970, Norman Abramson described the [ALOHA](#def-b2-link-layer-aloha) system, which linked terminals on several Hawaiian islands to one computer over a shared radio channel. Its rule was the simplest possible: send when you have a [frame](#def-b2-link-layer-frame); if no acknowledgement comes, wait a random time and send again.

In *slotted [ALOHA](#def-b2-link-layer-aloha)*, time is cut into slots of one [frame](#def-b2-link-layer-frame) each, and a station sends only at the start of a slot. A slot is useful when exactly one station sends. Let $n$ stations each send in a slot with probability $p = G/n$, so that $G$ [frames](#def-b2-link-layer-frame) are tried per slot on average.

**Proposition 17.12 (Slotted ALOHA).**

The fraction of useful slots is $S_n = G(1 - G/n)^{n-1}$, which tends to $S = G e^{-G}$ as $n$ grows. The maximum of $G e^{-G}$ is $1/e \approx 0.368$, at $G = 1$.

**Proof.** Exactly one station sends with probability $n \cdot p (1 - p)^{n-1} = G (1 - G/n)^{n-1}$: one of the $n$ sends, and the $n - 1$ others do not. As $n$ grows, $(1 - G/n)^{n} \to e^{-G}$ and $(1 - G/n)^{-1} \to 1$. The maximum is [Exercise 17.10](#exo-b2-link-layer-10). ∎

```
$ python aloha_sim.py
   G  simulated  G e^-G
0.25      0.194   0.195
0.50      0.308   0.303
0.75      0.351   0.354
1.00      0.369   0.368
1.25      0.362   0.358
1.50      0.340   0.335
1.75      0.309   0.304
2.00      0.267   0.271
2.25      0.239   0.237
2.50      0.205   0.205
2.75      0.177   0.176
3.00      0.147   0.149
```

***Output 17.9.** Slotted [ALOHA](#def-b2-link-layer-aloha) with 100 stations, 20 000 slots per value of $G$.*

![The points of against G e-G. Too few attempts leave slots empty; too many waste them in collisions. At best, 37 slots in 100 are useful.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-link-layer/fig-d6835dd2f945.svg)

*The points of [Output 17.9](#out-b2-link-layer-aloha) against $G e^{-G}$. Too few attempts leave slots empty; too many waste them in [collisions](#def-b2-link-layer-mac-protocol). At best, 37 slots in 100 are useful.*

On a cable, a station can do better: listen first. *Carrier sense multiple access with [collision](#def-b2-link-layer-mac-protocol) detection* ([CSMA/CD](#def-b2-link-layer-aloha)), the rule of the first Ethernets, sends only when the medium is quiet, keeps listening while sending, and stops as soon as it hears a [collision](#def-b2-link-layer-mac-protocol). It then waits a random number of slots before trying again, chosen by [binary exponential backoff](#def-b2-link-layer-aloha) (defined below): after its $c$-th [collision](#def-b2-link-layer-mac-protocol) on a [frame](#def-b2-link-layer-frame), a station waits a number of slots drawn uniformly from $0$ to $2^{\min(c,10)} - 1$. Each [collision](#def-b2-link-layer-mac-protocol) doubles the range, so the stations spread out until one gets through; [Exercise 17.9](#exo-b2-link-layer-9) measures the delay.

**Definition 17.13 (ALOHA, CSMA/CD, binary exponential backoff).**

In *ALOHA* a station sends whenever it has a [frame](#def-b2-link-layer-frame) and, after a [collision](#def-b2-link-layer-mac-protocol), again after a random delay; *slotted ALOHA* sends only at the start of a time slot. *CSMA/CD* senses the medium before sending and stops on hearing a [collision](#def-b2-link-layer-mac-protocol). *Binary exponential backoff* draws the delay after the $c$-th [collision](#def-b2-link-layer-mac-protocol) uniformly among $0, \dots, 2^{\min(c,10)} - 1$ slots.

Carrier sense fails on radio, where a station may not hear every other one. If $A$ and $C$ are both in range of $B$ but not of each other, each senses a quiet medium and sends to $B$, and their [frames](#def-b2-link-layer-frame) collide at $B$ without either hearing it.

**Definition 17.14 (Hidden terminal).**

A *hidden terminal* is a station whose transmissions reach a receiver but not another sender to that receiver, so that carrier sense cannot prevent their [collisions](#def-b2-link-layer-mac-protocol). Wireless networks therefore detect lost [frames](#def-b2-link-layer-frame) by the missing acknowledgement, and may reserve the medium first by a short exchange.

## 17.4 Ethernet and switches

**Definition 17.15 (MAC address, broadcast address).**

A *MAC address* is the 6-byte address of a network interface on its [link](#def-b2-link-layer-frame), written as six hexadecimal bytes, `02:00:00:00:00:01`. In the first byte, the lowest bit marks a *group* address (a [frame](#def-b2-link-layer-frame) for several receivers), and the next bit a *locally administered* one, chosen by its owner rather than by the maker. The address `ff:ff:ff:ff:ff:ff`, the *broadcast address*, means every interface on the [link](#def-b2-link-layer-frame).

An Ethernet [frame](#def-b2-link-layer-frame) has a 14-byte header (destination, source, type), a payload of 46 to 1500 bytes, shorter payloads being padded, and a 4-byte CRC-32. The type says what the payload is: `0800` an IPv4 packet, `0806` an ARP message ([Section 17.5](#sec-17-5)), `86dd` an IPv6 packet.

![An Ethernet frame. The CRC-32 covers the header and the payload; a frame is therefore 64 to 1518 bytes long.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-link-layer/fig-89610da2727c.svg)

*An Ethernet [frame](#def-b2-link-layer-frame). The CRC-32 covers the header and the payload; a [frame](#def-b2-link-layer-frame) is therefore 64 to 1518 bytes long.*

```python
def arp_request(sender_mac, sender_ip, target_ip):
    return (
        (1).to_bytes(2, "big")                 # hardware: Ethernet
        + (0x0800).to_bytes(2, "big")          # protocol: IPv4
        + bytes([6, 4])                        # address lengths
        + (1).to_bytes(2, "big")               # operation: request
        + sender_mac + sender_ip + bytes(6) + target_ip    # target MAC: unknown
    )


def ethernet(dst, src, ethertype, payload):
    body = dst + src + ethertype.to_bytes(2, "big") + payload.ljust(46, b"\0")
    return body + zlib.crc32(body).to_bytes(4, "little")   # the frame check

```

***Listing 17.6.** A [frame](#def-b2-link-layer-frame) built byte by byte code/bachelor-2/17-link-layer/listings/ethernet_frame.py*

```
$ python ethernet_frame.py
0000  ff ff ff ff ff ff 02 00 00 00 00 01 08 06 00 01
0010  08 00 06 04 00 01 02 00 00 00 00 01 0a 00 00 01
0020  00 00 00 00 00 00 0a 00 00 02 00 00 00 00 00 00
0030  00 00 00 00 00 00 00 00 00 00 00 00 e8 6f 4d f8
64 bytes: destination ff:ff:ff:ff:ff:ff, source 02:00:00:00:00:01
type 0806, payload 46 bytes (28 of ARP), check e86f4df8
source's first byte 02: group bit 0, local bit 1
receiver's check: True
```

***Output 17.10.** The 64 bytes of a broadcast [frame](#def-b2-link-layer-frame) carrying an ARP request.*

**Definition 17.16 (Network switch, switch table).**

A *network switch* is a box with many ports, each linked to a machine or another switch, that receives each [frame](#def-b2-link-layer-frame) and sends it on only through the ports where its destination may be. Its *switch table* maps MAC addresses to ports.

Machines on one Ethernet are connected by switches. A switch needs no configuration, because it learns its table.

**Method 17.17 (Self-learning switch).**

For each [frame](#def-b2-link-layer-frame) that arrives on port $p$: record in the table that its source is reachable through $p$. Then, if the destination is in the table on a port other than $p$, send the [frame](#def-b2-link-layer-frame) on that port only (*forward*); if it is in the table on port $p$, drop it (*filter*: the receiver already heard it); if it is not in the table, or is a broadcast, send it on every port except $p$ (*flood*).

```python
class Switch:
    def __init__(self, ports):
        self.ports = ports
        self.table = {}                       # MAC address -> port

    def receive(self, src, dst, port):
        """Return the ports the frame leaves by."""
        self.table[src] = port                # learn: src is reachable through port
        if dst in self.table:
            out = self.table[dst]
            return [] if out == port else [out]    # filter, or forward
        return [p for p in self.ports if p != port]   # unknown: flood

```

***Listing 17.7.** A self-learning switch code/bachelor-2/17-link-layer/listings/switch_sim.py*

```
$ python switch_sim.py
A -> B  flood to [2, 3, 4, 5]  table A:1
B -> A  forward to [1]  table A:1 B:2
C -> A  forward to [1]  table A:1 B:2 C:3
A -> C  forward to [3]  table A:1 B:2 C:3
E -> B  forward to [2]  table A:1 B:2 C:3 E:5
D -> F  flood to [1, 2, 3, 5]  table A:1 B:2 C:3 D:4 E:5
```

***Output 17.11.** Five hosts on ports 1 to 5; the table after each [frame](#def-b2-link-layer-frame).*

The first [frame](#def-b2-link-layer-frame) from $A$ is flooded, since nobody knows $B$ yet; $B$’s answer is forwarded, since $A$ is now known. After a few [frames](#def-b2-link-layer-frame) the switch floods only for unknown or broadcast destinations. Several switches can be connected in a tree, and learning works through them ([Exercise 17.5](#exo-b2-link-layer-5)). A loop, though, would make a flooded [frame](#def-b2-link-layer-frame) circle forever, each switch flooding it again. Real networks keep a spare cable for safety anyway; the switches then run the *spanning tree protocol*, in which they elect one switch as root and switch off the ports that would close a loop, leaving a tree, and switch a spare port on again when a cable fails.

![The plug of an Ethernet cable: eight gold contacts for four twisted pairs of copper wires. Photograph: David Monniaux, CC BY-SA 3.0.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-link-layer/img-ea64cdd67681.jpg)

*The plug of an Ethernet cable: eight gold contacts for four twisted pairs of copper wires. Photograph: David Monniaux, CC BY-SA 3.0.*

## 17.5 Address resolution

The layer above addresses machines by IP address ([Chapter 18](https://one-course.com/books/computer-science/4/en/chapter/18-the-network-layer-ip-and-routing#ch-b2-network-layer)); the [link](#def-b2-link-layer-frame) needs a [MAC address](#def-b2-link-layer-mac-address).

**Definition 17.18 (Address resolution).**

*Address resolution* finds the [MAC address](#def-b2-link-layer-mac-address) of the interface that holds a given IP address on the same [link](#def-b2-link-layer-frame); on Ethernet with IPv4 it is done by the *address resolution protocol* (ARP).

**Method 17.19 (ARP).**

To send to IP address $a$ on its [link](#def-b2-link-layer-frame), a machine looks $a$ up in its *ARP cache*. If the address is missing, it broadcasts a request (operation 1): “who has $a$? tell me, at this IP and [MAC address](#def-b2-link-layer-mac-address)”. The machine whose address is $a$ records the asker in its cache and sends a reply (operation 2) with its [MAC address](#def-b2-link-layer-mac-address); the asker records it. Entries expire after a while, so that a machine that changed its interface is found again.

The request of [Output 17.10](#out-b2-link-layer-frame) is such a broadcast: hardware type 1 (Ethernet), protocol `0800` (IPv4), address lengths 6 and 4, operation 1, the sender’s two addresses, an unknown target [MAC address](#def-b2-link-layer-mac-address) (zeros) and the target IP address `0a 00 00 02`, that is 10.0.0.2.

```
$ python arp_sim.py
t=  0  A: broadcast 'who has 10.0.0.3? tell 10.0.0.1'
        B: not mine, ignored
        C: reply '10.0.0.3 is at 02:00:00:00:00:03' to A
        A: frame sent to 02:00:00:00:00:03
t=  5  A: 10.0.0.3 is 02:00:00:00:00:03 (cache), frame sent
t=  9  C: 10.0.0.1 is 02:00:00:00:00:01 (cache), frame sent
t= 70  A: broadcast 'who has 10.0.0.3? tell 10.0.0.1'
        B: not mine, ignored
        C: reply '10.0.0.3 is at 02:00:00:00:00:03' to A
        A: frame sent to 02:00:00:00:00:03
```

***Output 17.12.** Three hosts; cache entries live 60 seconds in this simulation.*

![An ARP exchange. The request reaches everyone; the reply and the frame reach only their addressee. A second frame to C needs no request until the entry expires.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-link-layer/fig-5c44bb55c61b.svg)

*An ARP exchange. The request reaches everyone; the reply and the [frame](#def-b2-link-layer-frame) reach only their addressee. A second [frame](#def-b2-link-layer-frame) to C needs no request until the entry expires.*

ARP trusts every reply. A machine that answers for an address that is not its own receives the [frames](#def-b2-link-layer-frame) meant for it; networks defend against this by having switches check replies against the addresses they handed out, and by encrypting what travels above the [link](#def-b2-link-layer-frame), as the Year 3 volume explains.

## 17.6 Wireless links

A radio [link](#def-b2-link-layer-frame) differs from a cable in three ways. The signal weakens quickly with distance and through walls, so its error rate is far higher, and many wireless [links](#def-b2-link-layer-frame) resend a [frame](#def-b2-link-layer-frame) themselves: the receiver acknowledges each [frame](#def-b2-link-layer-frame), and the sender repeats it when no acknowledgement comes. Second, a station cannot listen while it sends, its own signal drowning every other, so it cannot detect a [collision](#def-b2-link-layer-mac-protocol). Third, not every station hears every other: these are the [hidden terminals](#def-b2-link-layer-hidden) of [Definition 17.14](#def-b2-link-layer-hidden), whose [frames](#def-b2-link-layer-frame) collide at the receiver. Wireless networks therefore *avoid* [collisions](#def-b2-link-layer-mac-protocol) (CSMA/CA): a station waits a random backoff even when the channel is quiet, and may first reserve the channel with a short request that the receiver answers with a short “clear to send”, which every station near the receiver, hidden or not, hears.

![Plugging a cable into a switch. Each port is a link of its own: the switch decides which links a frame crosses.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-link-layer/img-9c544f1b248b.jpg)

*Plugging a cable into a switch. Each port is a [link](#def-b2-link-layer-frame) of its own: the switch decides which [links](#def-b2-link-layer-frame) a [frame](#def-b2-link-layer-frame) crosses.*

## 17.7 Exercises

**Exercise 17.1 ★.**

Give the [even parity bits](#def-b2-link-layer-parity) of the bytes `0x4c`, `0x41`, `0x4d` and `0x50`, and check your answer against [Output 17.3](#out-b2-link-layer-parity). Which of the following errors does a [parity bit](#def-b2-link-layer-parity) per byte detect: one flip in each of two bytes; three flips in one byte; two flips in one byte?

**Solution of Exercise 17.1.**

`0x4c` $= 0100\,1100$ has three 1s, so its bit is 1; `0x41` $= 0100\,0001$, `0x4d` $= 0100\,1101$ and `0x50` $= 0101\,0000$ have two, four and two, so their bits are 0: `[1, 0, 0, 0]`, as printed. One flip in each of two bytes is detected, in both bytes; three flips in one byte are detected (an odd number); two flips in one byte are missed ([Proposition 17.5](#prop-b2-link-layer-parity)).

**Exercise 17.2 ★.**

This [checksum](#def-b2-link-layer-edc) forgets to add its carries back. Find the line, and explain why the first input gives the right value and the second does not.

```python
def checksum_nofold(data):
    total = 0
    for i in range(0, len(data), 2):
        total += data[i] << 8 | data[i + 1]
    return ~total & 0xFFFF
```

***Listing 17.8.** No folding code/bachelor-2/17-link-layer/listings/exo_nofold.py*

```
$ python exo_nofold.py
4c 41 4d 50  right 666e  without folding 666e
ff f0 00 20  right ffee  without folding ffef
```

***Output 17.13.** Right and wrong.*

**Solution of Exercise 17.2.**

The loop adds the words but never folds `total`; the final `~total & 0xFFFF` then throws the carries away instead of adding them back. For `LAMP`, $\mathtt{0x4c41} + \mathtt{0x4d50} = \mathtt{0x9991}$: no carry, so both versions agree. For `ff f0 00 20`, $\mathtt{0xfff0} + \mathtt{0x0020} = \mathtt{0x10010}$; the one’s complement sum is $\mathtt{0x0010} + 1 = \mathtt{0x0011}$, whose complement is `ffee`, while dropping the carry leaves `0x0010` and `ffef`. The bug shows only on data whose sum overflows, which is why a test on short text missed it. The fix is the line `total = (total & 0xFFFF) + (total >> 16)` in the loop.

**Exercise 17.3 ★.**

Write `correct(data, rows, col)`, which takes the data, its row [parity bits](#def-b2-link-layer-parity) and its column parity byte, corrects any single flipped bit (in the data or in the parities) and returns `None` when it cannot.

**Solution of Exercise 17.3.**

```python
def correct(data, rows, col):
    """Return the data with at most one flipped data bit corrected, or None."""
    bad_rows = [i for i, b in enumerate(data) if parity(b) != rows[i]]
    now = 0
    for b in data:
        now ^= b
    diff = now ^ col                          # columns whose parity is wrong
    if not bad_rows and diff == 0:
        return bytes(data)
    if len(bad_rows) == 1 and diff and diff & (diff - 1) == 0:
        out = bytearray(data)
        out[bad_rows[0]] ^= diff              # the one bit at the crossing
        return bytes(out)
    if len(bad_rows) == 1 and diff == 0:      # the row's own parity bit flipped
        return bytes(data)
    if not bad_rows and diff & (diff - 1) == 0:   # one bit of the parity byte
        return bytes(data)
    return None                               # more than one flip: give up
```

*Correcting one flip with a parity grid code/bachelor-2/17-link-layer/exercises/parity2d.py*

`diff` has a 1 in each column whose parity is wrong. One wrong row and one wrong column: the data bit at their crossing flipped, and XOR with `diff` puts it back. One wrong row and no wrong column: the row’s [parity bit](#def-b2-link-layer-parity) itself flipped, and the data is intact. No wrong row and one wrong column: a bit of the parity byte flipped. Anything else needs two flips or more. The test flips each of the 32 data bits, each row bit and each column bit, and checks that two flips in different rows give `None`.

**Exercise 17.4 ★.**

By long division, compute the 3 check bits of the message $1101\,0011$ with $g(x) = x^3 + x + 1$. Check that the [frame](#def-b2-link-layer-frame) sent is divisible by $g$.

**Solution of Exercise 17.4.**

Append three zeros and divide, XORing $1011$ under each leading 1:

$$
11010011\,000 \to 01100011\,000 \to 00111011\,000 \to 00010111\,000 \to 00000001\,000 \to 00000000\,011 .
$$

The check bits are $011$ and the [frame](#def-b2-link-layer-frame) is $11010011\,011$. Dividing the [frame](#def-b2-link-layer-frame) repeats the same steps, whose last three bits are now $011 + 011 = 000$: the remainder is 0. The test checks the value with `remainder`.

**Exercise 17.5 ★★.**

Two switches are connected by a cable between port 3 of $s_1$ and port 1 of $s_2$; hosts $A$ and $B$ are on ports 1 and 2 of $s_1$, $C$ and $D$ on ports 2 and 3 of $s_2$. Starting from empty tables, the [frames](#def-b2-link-layer-frame) $A \to C$, $C \to A$, $D \to B$, $B \to D$, $A \to B$, $D \to C$ are sent. Give both tables at the end, and say which [frames](#def-b2-link-layer-frame) were flooded by which switch.

**Solution of Exercise 17.5.**

```
$ python exo_switch.py
s1 A:1 B:2 C:3 D:3
s2 A:1 B:1 C:2 D:3
```

***Output 17.16.** The two tables after six [frames](#def-b2-link-layer-frame).*

$A \to C$: both switches learn $A$ and flood ($s_1$ on ports 2 and 3, $s_2$ on 2 and 3). $C \to A$: $s_2$ learns $C$ on 2 and forwards on 1; $s_1$ learns $C$ on 3 and forwards on 1. $D \to B$: nobody knows $B$, so $s_2$ floods on 1 and 2, and $s_1$ on 1 and 2; both learn $D$. $B \to D$, $A \to B$ and $D \to C$ are forwarded, $A \to B$ by $s_1$ alone. Each switch sees every host behind the other switch on the port of the cable: `C:3 D:3` in $s_1$, `A:1 B:1` in $s_2$. Two [frames](#def-b2-link-layer-frame) were flooded, by both switches.

**Exercise 17.6 ★★.**

This decoder drops the escape bytes. Explain its output and fix it.

```python
def unstuff_wrong(frame):
    return bytes(b for b in frame[1:-1] if b != 0x7D)
```

***Listing 17.9.** A wrong decoder code/bachelor-2/17-link-layer/listings/exo_unstuff.py*

```
$ python exo_unstuff.py
sent:    41 7e 42 7d 43
decoded: 41 5e 42 5d 43
```

***Output 17.14.** What came out.*

**Solution of Exercise 17.6.**

Stuffing sent `7e` as `7d 5e` and `7d` as `7d 5d`. The decoder drops each `7d` but leaves the byte after it as it is, so `5e` and `5d` come out instead of `7e` and `7d`. It must XOR the byte that follows an escape with `0x20`, as `unstuff` does. A second bug waits: a payload byte `7d` would be dropped too, if it ever arrived unescaped from a faulty sender; `unstuff` treats it as an escape, which at least keeps the rule in one place.

**Exercise 17.7 ★★.**

Write a CRC with the generator $x^8 + x^2 + x + 1$, most significant bit first, bit by bit and with a table of 256 entries, and test that they agree with each other and with `remainder` ([Listing 17.3](#lst-b2-link-layer-remainder)).

**Solution of Exercise 17.7.**

```python
def crc8_bitwise(data):
    crc = 0
    for byte in data:
        crc ^= byte
        for _ in range(8):
            crc = ((crc << 1) ^ G) & 0xFF if crc & 0x80 else (crc << 1) & 0xFF
    return crc


TABLE = [crc8_bitwise(bytes([b])) for b in range(256)]


def crc8_table(data):
    crc = 0
    for byte in data:
        crc = TABLE[crc ^ byte]               # the whole state is one byte
    return crc
```

*CRC-8, bit by bit and by table code/bachelor-2/17-link-layer/exercises/crc8.py*

With an 8-bit register and the message taken most significant bit first, each byte enters the register whole, so `TABLE[b]` is the CRC of the single byte $b$ and the table step needs no shift: the state after a byte is the table entry of the register XOR the byte. The test checks both against `remainder(m, 8n, 0x107)` on 40 random messages.

**Exercise 17.8 ★★.**

Prove [Proposition 17.10](#prop-b2-link-layer-crc-odd). Hint: for a polynomial $P$, $P(1)$ is the number of its terms modulo 2.

**Solution of Exercise 17.8.**

For a polynomial $P$, $P(1)$ is the sum of its coefficients, so it is the number of its terms modulo 2, and $(PQ)(1) =
P(1)Q(1)$, since evaluation respects products. Let $E$ be an error that passes the CRC: $g$ divides $E$, and $x + 1$ divides $g$, so $E = (x + 1)Q$ for some $Q$. Then $E(1) = (1 + 1)Q(1) = 0$: $E$ has an even number of terms, that is, an even number of flipped bits. So every error with an odd number of flips is detected.

**Exercise 17.9 ★★.**

Simulate $k$ stations that each have one [frame](#def-b2-link-layer-frame) to send at time 0 and follow [binary exponential backoff](#def-b2-link-layer-aloha) on a slotted channel. Measure the mean number of slots until every [frame](#def-b2-link-layer-frame) is through and the mean delay of a [frame](#def-b2-link-layer-frame), for $k = 2, 4,
\dots, 32$. How do they grow with $k$?

**Solution of Exercise 17.9.**

```python
def run(k, rng, cap=10):
    """Slots until every frame is through; and the mean slot at which a frame is."""
    wait = [0] * k                            # slots each station still waits
    collisions = [0] * k
    done, t, finish = set(), 0, []
    while len(done) < k:
        ready = [s for s in range(k) if s not in done and wait[s] == 0]
        if len(ready) == 1:
            done.add(ready[0])
            finish.append(t + 1)
        elif len(ready) > 1:                  # a collision: everyone in it backs off
            for s in ready:
                collisions[s] += 1
                wait[s] = rng.randrange(2 ** min(collisions[s], cap)) + 1
        for s in range(k):
            if s not in done and wait[s] > 0:
                wait[s] -= 1
        t += 1
    return t, sum(finish) / k
```

*[Binary exponential backoff](#def-b2-link-layer-aloha) code/bachelor-2/17-link-layer/listings/backoff_sim.py*

```
$ python backoff_sim.py
 k  slots to finish  mean delay of a frame (slots)
 2              5.2            4.5
 4             14.1            9.0
 8             37.7           18.8
16             99.1           39.6
32            240.9           78.6
```

***Output 17.17.** 2000 runs per value of $k$.*

A [collision](#def-b2-link-layer-mac-protocol) costs one slot here, an idealisation of [CSMA/CD](#def-b2-link-layer-aloha). The mean delay of a [frame](#def-b2-link-layer-frame) grows about linearly, close to $2.4k$ slots: the stations spread out until the window is about as large as their number, and then go through roughly one at a time. The time until the last [frame](#def-b2-link-layer-frame) grows faster, about 2.5 times per doubling of $k$: the unlucky stations have collided many times and wait in windows much larger than needed. That unfairness is the known weakness of exponential backoff.

**Exercise 17.10 ★★★.**

Prove that $G e^{-G}$ is largest at $G = 1$. In *pure* [ALOHA](#def-b2-link-layer-aloha), a station sends whenever it likes; a [frame](#def-b2-link-layer-frame) is lost if any other [frame](#def-b2-link-layer-frame) starts within one [frame](#def-b2-link-layer-frame) time before or after it. With attempts forming a Poisson process of $G$ [frames](#def-b2-link-layer-frame) per [frame](#def-b2-link-layer-frame) time, the throughput is $G e^{-2G}$. Find its maximum, and explain the factor 2.

**Solution of Exercise 17.10.**

$\frac{d}{dG}\,G e^{-G} = (1 - G)e^{-G}$, positive for $G < 1$ and negative after: the maximum is at $G = 1$, and it is $1/e \approx 0.368$. In pure [ALOHA](#def-b2-link-layer-aloha), a [frame](#def-b2-link-layer-frame) sent at time $t$ survives if no other [frame](#def-b2-link-layer-frame) starts in $(t - 1, t + 1)$: one starting just before overlaps its beginning, one starting just after its end. That interval has length 2 [frame](#def-b2-link-layer-frame) times, so with Poisson attempts no other start falls in it with probability $e^{-2G}$, and the throughput is $G
e^{-2G}$. Its derivative is $(1 - 2G)e^{-2G}$, so the maximum is at $G = 1/2$ and equals $1/(2e) \approx 0.184$: half of slotted [ALOHA](#def-b2-link-layer-aloha)’s, because slots halve the vulnerable interval.

**Exercise 17.11 ★★★.**

Show that a [burst](#def-b2-link-layer-burst) $x^i B(x)$ passes a CRC exactly when $B$ does, so that checking every [burst](#def-b2-link-layer-burst) on a [frame](#def-b2-link-layer-frame) reduces to checking every pattern $B$ once. For CRC-16, count the patterns of lengths 17 and 18 that pass, compare with [Output 17.6](#out-b2-link-layer-bursts), and explain both counts.

**Solution of Exercise 17.11.**

The proof of [Theorem 17.9](#thm-b2-link-layer-crc-burst) shows that if $g$ divides $x C$ then it divides $C$; conversely, if $g$ divides $C$ it divides $xC$. So $g$ divides $x^i B$ exactly when it divides $B$, whatever the position $i$.

```
$ python burst_fraction.py
length  2:      1 patterns, 0 divisible by g
length 16:  16384 patterns, 0 divisible by g
length 17:  32768 patterns, 1 divisible by g
length 18:  65536 patterns, 1 divisible by g
```

***Output 17.18.** Every pattern of a [burst](#def-b2-link-layer-burst), checked once.*

A [burst](#def-b2-link-layer-burst) of length 17 is $B$ of degree 16 with constant term 1. If $g$ divides it, $B = gQ$ with $Q$ of degree 0, so $B = g$: one pattern in $2^{15}$. In [Output 17.6](#out-b2-link-layer-bursts), that one pattern sits at each of the $48 - 17 + 1
= 32$ positions, hence 32. For length 18, $Q$ has degree 1 and its constant term must be 1 (as $B(0) = g(0)Q(0)$), so $Q = x + 1$: one pattern in $2^{16}$. In general, for [bursts](#def-b2-link-layer-burst) longer than $r + 1$ the fraction is $2^{-r}$.

**Exercise 17.12 ★★★.**

On [frames](#def-b2-link-layer-frame) of $N \ge r$ bits, show that exactly $2^{N-r} - 1$ of the $2^N - 1$ nonzero error patterns pass a CRC of degree $r$, about one in $2^r$. With $x + 1$ dividing $g$, what fraction of the patterns with an even number of flips pass?

**Solution of Exercise 17.12.**

An error pattern on $N$ bits is a polynomial $E$ of degree less than $N$, and it passes when $E = gQ$. Each $Q$ of degree less than $N - r$ gives such an $E$, and different $Q$ give different $E$; conversely the quotient of a multiple of $g$ of degree less than $N$ has degree less than $N - r$. There are $2^{N-r}$ such $Q$, one of them 0, so $2^{N-r} - 1$ nonzero patterns pass out of $2^N - 1$, about $2^{-r}$. If $x + 1$ divides $g$, every multiple of $g$ has an even number of terms ([Exercise 17.8](#exo-b2-link-layer-8)), and the even patterns, $2^{N-1}$ of them (with 0), contain all $2^{N-r}$ multiples: a fraction $2^{-(r-1)}$ of them pass, twice the average, while no odd pattern passes.

## 17.8 Problem: The noisy link to the lighthouse

**Problem 17.1.**

Weekend problem — The noisy link to the lighthouse

The harbour sends short [frames](#def-b2-link-layer-frame) to the lighthouse over a radio [link](#def-b2-link-layer-frame): a 4-byte command followed by 16 check bits of CRC-16, with $g(x) = x^{16} + x^{12} + x^5 + 1$. Noise comes in [bursts](#def-b2-link-layer-burst).

**Part I — Framing.**

1. [Frames](#def-b2-link-layer-frame) are separated by the flag `0x7e` . Stuff the payload `7d 7e 00 7e` .
2. What is the longest a stuffed payload of $n$ bytes can be, and for which payloads?
3. Both flags between two [frames](#def-b2-link-layer-frame) are lost in the noise. What does the receiver see, and does the CRC of this problem catch it?
4. Why does the CRC cover the payload before stuffing rather than after?
5. The lighthouse could instead receive a length byte before each payload. Why is a length byte risky on a noisy [link](#def-b2-link-layer-frame) , where a flag is not?
6. How many bytes cross the [link](#def-b2-link-layer-frame) for the command `LAMP` , its check and two flags?

**Part II — Detecting errors.**

7. The last line of the output of `crc.py` gives the check bits of `LAMP` . Write the 6 bytes sent, and say why the receiver’s CRC of the whole [frame](#def-b2-link-layer-frame) is 0.
8. Why can one [parity bit](#def-b2-link-layer-parity) per [frame](#def-b2-link-layer-frame) not protect this [link](#def-b2-link-layer-frame) against [bursts](#def-b2-link-layer-burst) ?
9. Using [Theorem 17.9](#thm-b2-link-layer-crc-burst) , which [bursts](#def-b2-link-layer-burst) is CRC-16 sure to detect?
10. Using [Proposition 17.10](#prop-b2-link-layer-crc-odd) , which other errors is it sure to detect?
11. In [Output 17.6](#out-b2-link-layer-bursts) , why are there 32 undetected [bursts](#def-b2-link-layer-burst) of length 17 and not more?
12. The listing below draws $2^{24}$ random error patterns on the 48-bit [frame](#def-b2-link-layer-frame). What count of undetected patterns does [Exercise 17.12](#exo-b2-link-layer-12) predict? Compare with the output. `$ python random_errors.py random error patterns: 16777216 undetected: 256, expected about 256 with an even number of flips: 256; with an odd number: 0` **Output 17.15.** Random error patterns through CRC-16.

**Part III — Sharing the radio channel.**

13. Five buoys report to the harbour on the same channel with slotted [ALOHA](#def-b2-link-layer-aloha) . Each sends in a slot with probability $p$ . What is the probability that a slot is useful?
14. Which $p$ makes it largest, and what is the largest value? Compare with $1/e$ .
15. Why can the buoys not use [collision](#def-b2-link-layer-mac-protocol) detection?
16. The lighthouse and a buoy behind the headland both hear the harbour, but not each other. Name the problem and say what it causes.
17. How does a short reservation exchange help, and what does it cost?
18. Why does every [frame](#def-b2-link-layer-frame) need an acknowledgement on this [link](#def-b2-link-layer-frame) , when a cable often needs none?

**Part IV — Choosing a CRC.**

19. [Bursts](#def-b2-link-layer-burst) of up to 20 bits are common on this [link](#def-b2-link-layer-frame) . Is CRC-16 enough? What does CRC-32 guarantee instead?
20. What does CRC-32 cost per [frame](#def-b2-link-layer-frame) , in bytes and in computation, against CRC-16?
21. A [frame](#def-b2-link-layer-frame) carries 4 bytes of data. What fraction of the [frame](#def-b2-link-layer-frame) is check bits with each CRC?
22. [Bursts](#def-b2-link-layer-burst) of 20 bits occur in one [frame](#def-b2-link-layer-frame) in a thousand. Estimate how many corrupted [frames](#def-b2-link-layer-frame) CRC-16 lets through per million [frames](#def-b2-link-layer-frame) .
23. Why is a CRC computed by a table in software, or by a shift register in hardware, rather than by the bit-by-bit division of [Listing 17.3](#lst-b2-link-layer-remainder) ?
24. State the result: no [burst](#def-b2-link-layer-burst) of 16 bits or fewer passes CRC-16, and random errors pass at the predicted rate $2^{-16}$ , with the counts of the simulation.

**Solution of Problem 17.1.**

**1.** `7e 7d 5d 7d 5e 00 7d 5e 7e`: each `7d` and `7e` becomes two bytes.

**2.** $2n$ bytes (plus the two flags), when every byte of the payload is `7e` or `7d`.

**3.** Two [frames](#def-b2-link-layer-frame) run together into one, of 12 bytes. The CRC does not catch it: it is accepted every time, not with probability $2^{-16}$. Each [frame](#def-b2-link-layer-frame) $T_1$, $T_2$, check included, is a multiple of $g$, and with a register that starts at zero and no final complement the merged [frame](#def-b2-link-layer-frame) is $T_1(x)\,x^{48} + T_2(x)$, a multiple of $g$ too, so its check is 0. Only a length check (6 bytes expected) rejects it, or a CRC whose register starts at all ones, as real [links](#def-b2-link-layer-frame) use: then the second [frame](#def-b2-link-layer-frame)’s check no longer matches what comes before it. (With one flag lost the [frames](#def-b2-link-layer-frame) stay apart, since `stuffing.py` puts two flags between [frames](#def-b2-link-layer-frame).)

**4.** The check protects the command, whatever the framing; the receiver removes the stuffing first, then checks. The check bytes are stuffed like the payload, so a check that contains `7e` cannot end a [frame](#def-b2-link-layer-frame) early.

**5.** If the length byte is hit, the receiver reads the wrong number of bytes, takes the wrong place for the next length, and every later [frame](#def-b2-link-layer-frame) is misread until something resynchronises it. A damaged flag costs only the [frames](#def-b2-link-layer-frame) on both sides of it: the next flag is found again.

**6.** `LAMP` is `4c 41 4d 50` and its check is `2a 56`; none is `7e` or `7d`, so 6 bytes plus 2 flags: 8 bytes.

**7.** `4c 41 4d 50 2a 56`. The [frame](#def-b2-link-layer-frame) is $T = M x^{16} + R$, a multiple of $g$; the receiver’s CRC is the remainder of $T x^{16}$ by $g$, which is 0.

**8.** A [burst](#def-b2-link-layer-burst) often flips an even number of bits, which one [parity bit](#def-b2-link-layer-parity) never sees.

**9.** Every [burst](#def-b2-link-layer-burst) of 16 bits or fewer.

**10.** Every error with an odd number of flipped bits, since $g(1) = 1 + 1 + 1 + 1 = 0$, so $x + 1$ divides $g$.

**11.** A [burst](#def-b2-link-layer-burst) of 17 bits passes only if its pattern is $g$ itself ([Exercise 17.11](#exo-b2-link-layer-11)): one pattern per position, and there are $48 - 17 + 1 = 32$ positions.

**12.** $2^{24} \times (2^{32} - 1)/(2^{48} - 1) \approx 2^{24}/2^{16} = 256$. The simulation counted 256, all with an even number of flips, as [Proposition 17.10](#prop-b2-link-layer-crc-odd) demands. That it is exactly 256 is luck: the standard deviation of such a count is about $\sqrt{256} = 16$.

**13.** Exactly one of the five sends: $5p(1 - p)^4$.

**14.** The derivative is $5(1 - p)^3(1 - 5p)$, zero at $p = 1/5$, where the value is $(4/5)^4 \approx 0.410$, more than $1/e \approx 0.368$: with few stations the useful fraction $S_n = (1 - 1/n)^{n-1}$ at its best is larger, and it decreases to $1/e$ as $n$ grows.

**15.** A radio cannot hear while it sends: its own signal is far stronger than any other at its antenna. And the [collision](#def-b2-link-layer-mac-protocol) that matters happens at the receiver, which the sender may not hear at all.

**16.** The [hidden terminal](#def-b2-link-layer-hidden) problem: each finds the channel quiet, both send, and their [frames](#def-b2-link-layer-frame) collide at the harbour, which receives neither; neither sender knows.

**17.** A sender first sends a short request; the harbour answers with a short “clear to send”, heard by every station near the harbour, the hidden one included, which then keeps quiet for the time announced. [Collisions](#def-b2-link-layer-mac-protocol) can now hit only the short requests. The cost is two short [frames](#def-b2-link-layer-frame) and their delay for every data [frame](#def-b2-link-layer-frame), which pays only for long [frames](#def-b2-link-layer-frame).

**18.** Noise and [collisions](#def-b2-link-layer-mac-protocol) lose far more [frames](#def-b2-link-layer-frame) on radio than on a cable, and the sender cannot detect a [collision](#def-b2-link-layer-mac-protocol); an acknowledgement on the [link](#def-b2-link-layer-frame) lets it resend at once, instead of leaving the loss to the much slower layers above.

**19.** No: [bursts](#def-b2-link-layer-burst) of 17 to 20 bits each pass with probability about $2^{-15}$ or $2^{-16}$ ([Exercise 17.11](#exo-b2-link-layer-11)). CRC-32 detects every [burst](#def-b2-link-layer-burst) of up to 32 bits.

**20.** Two more bytes per [frame](#def-b2-link-layer-frame). With tables, the computation is one lookup per byte in both cases; the table grows from 512 bytes to 1 KiB.

**21.** $2/6 = 1/3$ with CRC-16; $4/8 = 1/2$ with CRC-32.

**22.** A [burst](#def-b2-link-layer-burst) of 20 bits passes with probability $2^{-16}$ (its pattern must be $gQ$ with $Q$ of degree 3 and constant term 1: 4 patterns of $2^{18}$). Per million [frames](#def-b2-link-layer-frame), 1000 have such a [burst](#def-b2-link-layer-burst), and $1000 \times 2^{-16}
\approx 0.015$ pass: about one bad command in 65 million [frames](#def-b2-link-layer-frame).

**23.** A table does in one lookup what takes eight shifts and tests; a hardware shift register with a few XOR gates handles each bit as it arrives on the wire, at the speed of the [link](#def-b2-link-layer-frame), with no memory at all.

**24.** Of 1 114 111 [bursts](#def-b2-link-layer-burst) of 1 to 16 bits, none passed CRC-16; of $2^{24} = 16\,777\,216$ random error patterns, 256 passed, the predicted $2^{24} \cdot 2^{-16}$, all of them with an even number of flips.
