---
title: "How the Internet Works"
book: "Primary & Middle School Computer Science"
subject: computer-science
language: en
chapter: 29
exercises: 12
source: https://one-course.com/books/computer-science/1/en/chapter/29-how-the-internet-works
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 29 — How the Internet Works

Sami takes a photo of a fox in the garden and sends it to his cousin on the other side of the world. Moments later, she sees it. On the way, the photo was cut into about two thousand pieces, which did not all travel the same way, passed through many machines that had never heard of Sami, and were put back together in the right order. This chapter follows those pieces.

**You already know.**

A [network](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-network) joins [computers](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-computer) so that they can exchange data; the [Internet](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-internet) joins [networks](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-network) across the world; a [server](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-server) keeps pages and sends them to the [browsers](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-page) that ask; a [web address](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-address) names a [server](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-server) and a [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) ([Chapter 13](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#ch-g5-networks-first-look)). A [byte](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) is 8 [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit), and holds a number from 0 to 255; $n$ [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) make $2^n$ patterns ([Chapter 25](https://one-course.com/books/computer-science/1/en/chapter/25-binary-and-hexadecimal#ch-g8-binary-and-hexadecimal)). A [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary) gives the [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of a key ([Chapter 26](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#ch-g8-dictionaries)).

## 29.1 Messages cut into packets

**Definition 29.1 (Packet, packet header).**

A *packet* is a small piece of the data sent over a [network](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-network), with a *packet header*: a few [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) in front that say where the packet comes from, where it goes, and which piece it is.

A [network](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-network) never sends a big [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) in one go. It cuts it into [packets](#def-g8-how-the-internet-works-packet) that travel one by one, each on its own, like the pages of a long letter posted in separate envelopes. The machine that receives them puts the pieces back in the order of their numbers. The [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) below does the same with a short message, with [packets](#def-g8-how-the-internet-works-packet) of 6 [characters](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string); the [packets](#def-g8-how-the-internet-works-packet) arrive in a mixed order, fixed in the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program).

```python
def cut(message, size, source, destination):
    """Cut a message into packets of at most size characters, each with a header."""
    packets = []
    number = 0
    for start in range(0, len(message), size):
        packets.append({"from": source, "to": destination, "number": number,
                        "data": message[start:start + size]})
        number = number + 1
    return packets


def rebuild(packets):
    """Put the pieces back in the order of their numbers."""
    pieces = {}
    for packet in packets:
        pieces[packet["number"]] = packet["data"]
    message = ""
    for number in range(len(pieces)):
        message = message + pieces[number]
    return message


if __name__ == "__main__":
    packets = cut("A fox in the garden at dusk!", 6, "192.0.2.15", "203.0.113.40")
    first = packets[0]
    print(len(packets), "packets; from", first["from"], "to", first["to"])
    arrived = [packets[3], packets[0], packets[4], packets[1], packets[2]]
    for packet in arrived:
        print(packet["number"], repr(packet["data"]))
    print(rebuild(arrived))
```

***Listing 29.1.** Cutting a message into [packets](#def-g8-how-the-internet-works-packet), then rebuilding it. code/grade-8/05-how-the-internet-works/listings/packets.py*

```
$ python packets.py
5 packets; from 192.0.2.15 to 203.0.113.40
3 'n at d'
0 'A fox '
4 'usk!'
1 'in the'
2 ' garde'
A fox in the garden at dusk!
```

***Output 29.1.** The [packets](#def-g8-how-the-internet-works-packet) arrive out of order; their numbers put them back.*

![A photo cut into numbered packets, each with a small header in front of its data; they arrive in another order, and their numbers put them back.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-how-the-internet-works/fig-823560f1a2a8.svg)

*A photo cut into numbered [packets](#def-g8-how-the-internet-works-packet), each with a small header in front of its data; they arrive in another order, and their numbers put them back.*

What if a [packet](#def-g8-how-the-internet-works-packet) is lost on the way? The rebuilt message has a hole:

```python
from packets import cut

packets = cut("A fox in the garden at dusk!", 6, "192.0.2.15", "203.0.113.40")
arrived = [packets[3], packets[0], packets[4], packets[2]]       # number 1 is lost

pieces = {}
for packet in arrived:
    pieces[packet["number"]] = packet["data"]
message = ""
for number in range(len(packets)):
    message = message + pieces.get(number, "______")     # a hole for a lost piece
print(message)
```

***Listing 29.2.** One [packet](#def-g8-how-the-internet-works-packet) never arrives. code/grade-8/05-how-the-internet-works/listings/lost_packet.py*

```
$ python lost_packet.py
A fox ______ garden at dusk!
```

***Output 29.2.** A hole where [packet](#def-g8-how-the-internet-works-packet) 1 should be.*

The receiving machine sees which number is missing and asks for that [packet](#def-g8-how-the-internet-works-packet) again. Only the lost piece is sent twice, not the whole photo: that is one reason for cutting it up.

## 29.2 An address for every machine

**Definition 29.2 (IP address).**

An *IP address* is the number that identifies a machine on the [Internet](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-internet). In its common form it is four [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte), written as four numbers from 0 to 255 separated by dots, such as `192.168.1.20`.

Four [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) are 32 [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit). The [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) cuts an address at its dots and writes each part in [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary) on 8 digits, with the [f-string](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string) layout `08b`: `b` for [binary](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-binary), `08` for 8 digits with zeros in front.

```python
address = "192.168.1.20"
parts = address.split(".")
bits = ""
for part in parts:
    byte = int(part)
    print(part.rjust(3), "->", f"{byte:08b}")
    bits = bits + f"{byte:08b}"
print(len(parts), "bytes,", len(bits), "bits:", bits)
```

***Listing 29.3.** An [IP address](#def-g8-how-the-internet-works-ip-address) as four [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte). code/grade-8/05-how-the-internet-works/listings/ip_bytes.py*

```
$ python ip_bytes.py
192 -> 11000000
168 -> 10101000
  1 -> 00000001
 20 -> 00010100
4 bytes, 32 bits: 11000000101010000000000100010100
```

***Output 29.3.** 32 [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit).*

![The address 192.168.1.20 as 32 bits: four bytes, each written in decimal between the dots.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-how-the-internet-works/fig-d942467d31eb.svg)

*The address `192.168.1.20` as 32 [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit): four [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte), each written in decimal between the dots.*

How many such addresses exist? $2^{32}$:

```python
print("4 bytes:", 2**32, "addresses")
print("16 bytes:", 2**128, "addresses")
print("people on Earth: about 8,000,000,000")
```

***Listing 29.4.** Counting the addresses. code/grade-8/05-how-the-internet-works/listings/count_addresses.py*

```
$ python count_addresses.py
4 bytes: 4294967296 addresses
16 bytes: 340282366920938463463374607431768211456 addresses
people on Earth: about 8,000,000,000
```

***Output 29.4.** Fewer [four-byte](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) addresses than people.*

About 4.3 billion addresses are fewer than the people on Earth, and many people own several machines. The newer addresses therefore use 16 [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte), 128 [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit): $2^{128}$ is a number of 39 digits, enough for every grain of sand many times over. Both kinds are in use today.

**Definition 29.3 (Network interface).**

A *network interface* is the part of a machine that connects it to a [network](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-network): a socket for a cable, or a radio for wi-fi. A machine has an address for each of its [network](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-network) interfaces.

**Definition 29.4 (Network switch).**

A *network switch* is a box with many sockets that joins the machines of one local [network](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-network), such as those of a home, a school or an office, and passes each [packet](#def-g8-how-the-internet-works-packet) to the machine it is for.

![An optical fibre cable made to be buried in the ground, opened: the red and the green tube each hold 12 coloured glass fibres, each one carrying its own flashes of light.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-how-the-internet-works/img-49fd1d57aea4.jpg)

*An optical fibre cable made to be buried in the ground, opened: the red and the green tube each hold 12 coloured glass fibres, each one carrying its own flashes of light.*

At home, the box from the [Internet](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-internet) provider usually contains a small switch and a wi-fi radio: the laptop, the phone and the printer of the house are on one local [network](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-network). Over long distances, the [packets](#def-g8-how-the-internet-works-packet) travel as flashes of light in optical fibres, glass threads thinner than a hair.

## 29.3 Routers

**Definition 29.5 (Router).**

A *router* is a machine that joins [networks](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-network). For each [packet](#def-g8-how-the-internet-works-packet) it receives, it reads the destination address in the header and passes the [packet](#def-g8-how-the-internet-works-packet) one step closer to it, to the next router or to the local [network](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-network) of the destination.

No [router](#def-g8-how-the-internet-works-router) knows the whole [Internet](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-internet). Each one keeps a table of directions: “for these addresses, pass to that neighbour”. The [packet](#def-g8-how-the-internet-works-packet) hops from [router](#def-g8-how-the-internet-works-router) to [router](#def-g8-how-the-internet-works-router), each choosing only the next step. The [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) below uses a toy [network](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-network) of six [routers](#def-g8-how-the-internet-works-router), A to F, with a [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary) that gives each [router](#def-g8-how-the-internet-works-router)’s next step towards F.

```python
# For a packet going to router F, each router knows only the next router to pass it to.
next_step = {"A": "B", "B": "C", "C": "F", "D": "E", "E": "F"}

router = "A"
path = [router]
while router != "F":
    router = next_step[router]
    path.append(router)
print(" -> ".join(path), "in", len(path) - 1, "steps")
```

***Listing 29.5.** The path of a [packet](#def-g8-how-the-internet-works-packet), one step at a time. code/grade-8/05-how-the-internet-works/listings/path.py*

```
$ python path.py
A -> B -> C -> F in 3 steps
```

***Output 29.5.** Three hops.*

![Two local networks, each joined by a switch, linked through routers. In red, the path of : A, B, C, F.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-how-the-internet-works/fig-8f1ca7386c4f.svg)

*Two local [networks](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-network), each joined by a switch, linked through [routers](#def-g8-how-the-internet-works-router). In red, the path of [Listing 29.5](#lst-g8-how-the-internet-works-path): A, B, C, F.*

If a link breaks, the [routers](#def-g8-how-the-internet-works-router) change their tables, and the next [packets](#def-g8-how-the-internet-works-packet) go round the break: the [packets](#def-g8-how-the-internet-works-packet) of one message may well take different paths.

**History — The first network of networks.**

The ancestor of the [Internet](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-internet), the ARPANET, was switched on in late October 1969 in the United States. It was the first large [network](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-network) built to connect different kinds of [computers](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-computer) together.

## 29.4 Names turned into addresses

**Definition 29.6 (Domain name, domain name system).**

A *domain name* is a name for a machine on the [Internet](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-internet), made of words separated by dots, such as `library.brenmoor.example`. The *domain name system* (DNS) is a service, spread over many [servers](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-server), that answers the question “which [IP address](#def-g8-how-the-internet-works-ip-address) does this name have?”.

People remember names; [routers](#def-g8-how-the-internet-works-router) need numbers. Before anything else, a [browser](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-page) asks the name system for the address of the name in the [web address](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-address). The toy version is a [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary):

```python
names = {
    "library.brenmoor.example": "203.0.113.7",
    "weather.brenmoor.example": "203.0.113.12",
    "school.brenmoor.example": "198.51.100.30",
}


def look_up(name):
    """The address of a name, as the name system answers it, or None."""
    return names.get(name)


for name in ["weather.brenmoor.example", "pool.brenmoor.example"]:
    print(name, "->", look_up(name))
```

***Listing 29.6.** A toy name table. code/grade-8/05-how-the-internet-works/listings/names.py*

```
$ python names.py
weather.brenmoor.example -> 203.0.113.12
pool.brenmoor.example -> None
```

***Output 29.6.** An unknown name has no address.*

The names ending in `.example` and the addresses starting with `192.0.2`, `198.51.100` and `203.0.113` are kept for examples in books like this one: they belong to no real machine.

## 29.5 From typing an address to seeing the page

**Definition 29.7 (Client).**

A *client* is a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that asks a [server](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-server) for something, such as a [browser](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-page) asking for a page. The client asks; the [server](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-server) answers.

![From a typed name to a page on the screen: the name system gives the address, the client asks the server, and the page comes back in packets.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-how-the-internet-works/fig-366c265f9028.svg)

*From a typed name to a page on the screen: the name system gives the address, the [client](#def-g8-how-the-internet-works-client) asks the [server](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-server), and the page comes back in [packets](#def-g8-how-the-internet-works-packet).*

Typing `library.brenmoor.example` in the address bar sets off the whole chain of this chapter: the name becomes an address; the request travels in [packets](#def-g8-how-the-internet-works-packet), through switches and [routers](#def-g8-how-the-internet-works-router), to the [server](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-server); the page comes back in [packets](#def-g8-how-the-internet-works-packet), maybe by other paths; the [browser](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-page) puts them in order and draws the page. It usually takes less than a second.

## 29.6 Speed and delay

**Definition 29.8 (Bit rate).**

The *bit rate* of a connection is the number of [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) it can send each second, in [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) per second; a megabit per second (Mbit/s) is a million of them.

**Definition 29.9 (Latency).**

The *latency* of a connection is the time a [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) takes to reach the other end: the delay before anything arrives, however fast the [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) follow each other after that.

[Bit rate](#def-g8-how-the-internet-works-bit-rate) is the width of a pipe, [latency](#def-g8-how-the-internet-works-latency) its length. Part of the [latency](#def-g8-how-the-internet-works-latency) is the travel of the light itself: in a glass fibre, light covers about 200,000 kilometres each second, two thirds of its speed in empty space.

```python
speed = 300_000 * 2 / 3            # light in a glass fibre: about 200,000 km per second

for km in [10, 1_000, 20_000]:
    seconds = km / speed
    print(f"{km:>6} km: {seconds * 1000:.2f} ms")

photo_bits = 3_000_000 * 8         # a photo of 3 megabytes
rate = 10_000_000                  # 10 megabits per second
print("sending the photo:", photo_bits / rate, "s")
```

***Listing 29.7.** The travel time over a few distances, and the time to send a photo. code/grade-8/05-how-the-internet-works/listings/delay.py*

```
$ python delay.py
    10 km: 0.05 ms
  1000 km: 5.00 ms
 20000 km: 100.00 ms
sending the photo: 2.4 s
```

***Output 29.7.** One millisecond (ms) is a thousandth of a second.*

Across a town, the light travel is nothing; across half the world, it is a tenth of a second, and no faster connection can shorten it. Sending the 3 [megabytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-units) of a photo, $3{,}000{,}000 \times 8 = 24$ million [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit), at 10 megabits per second takes 2.4 seconds: there, a faster connection helps.

**Facts as of 2026.**

In the United Kingdom, the telecoms regulator reported that the home connections in use could reach 285 megabits per second on average in 2025, against 223 in 2024; most homes with optical fibre chose a plan of 300 megabits per second or less. Fast home plans reach 1,000 megabits per second, a gigabit.

The data centres that hold the [servers](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-server) of the [Internet](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-internet) used about 415 terawatt-hours of electricity in 2024, about 1.5 % of the world’s electricity, according to the International Energy Agency.

![In a data centre, rows of cabinets hold servers, switches and routers, joined by cables and optical fibres.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-how-the-internet-works/img-48fd1cd80568.jpg)

*In a data centre, rows of cabinets hold [servers](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-server), switches and [routers](#def-g8-how-the-internet-works-router), joined by cables and optical fibres.*

## 29.7 Exercises

**Exercise 29.1 ★.**

What does [Listing 29.3](#lst-g8-how-the-internet-works-ip) print for the address `10.0.0.255`?

**Solution of Exercise 29.1.**

The four parts, then the 32 [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit): `10 -> 00001010`, `0 -> 00000000`, `0 -> 00000000`, `255 -> 11111111`, and `4 bytes, 32 bits: 00001010000000000000000011111111`.

**Exercise 29.2 ★.**

Four [packets](#def-g8-how-the-internet-works-packet) arrive in this order: (2, `"ld"`), (0, `"Hel"`), (3, `"!"`), (1, `"lo wor"`). What is the rebuilt message?

**Solution of Exercise 29.2.**

In the order of the numbers 0, 1, 2, 3: `"Hel"`, `"lo wor"`, `"ld"`, `"!"`, which make `"Hello world!"`.

**Exercise 29.3 ★.**

What does [Listing 29.5](#lst-g8-how-the-internet-works-path) print if the [packet](#def-g8-how-the-internet-works-packet) starts at [router](#def-g8-how-the-internet-works-router) D?

**Solution of Exercise 29.3.**

`D -> E -> F in 2 steps`: the [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary) gives E after D, and F after E.

**Exercise 29.4 ★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `cut(text, size)` that cuts a text into pieces of at most `size` [characters](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string), numbered from 1, each a [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary) with the keys `"number"`, `"of"` (how many pieces there are in all, so that the receiver knows when every piece has come) and `"data"`.

**Solution of Exercise 29.4.**

The number of pieces is known before cutting: it is the length divided by the size, rounded up, the trick of the buses of [Chapter 14](https://one-course.com/books/computer-science/1/en/chapter/14-a-first-python-program#ch-g6-first-python-program). The number of a new piece is one more than the number of pieces made so far:

```python
def cut(text, size):
    """Cut text into pieces numbered from 1, each one knowing how many there are."""
    total = (len(text) + size - 1) // size
    pieces = []
    for start in range(0, len(text), size):
        data = text[start:start + size]
        pieces.append({"number": len(pieces) + 1, "of": total, "data": data})
    return pieces


for piece in cut("Meet me at the lighthouse at six.", 10):
    print(piece)
```

*Numbered pieces that know how many there are. code/grade-8/05-how-the-internet-works/exercises/cut10.py*

With `"Meet me at the lighthouse at six."` (33 [characters](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string)) and 10, `(33 + 9) // 10` is 4: four pieces, `"Meet me at"`, `" the light"`, `"house at s"` and `"ix."`, numbered 1 to 4, each `"of": 4`.

**Exercise 29.5 ★★.**

This rebuild keeps the numbers as text. With 12 [packets](#def-g8-how-the-internet-works-packet) of one letter, from `"a"` to `"l"`, it returns `"abklcdefghij"`. Why? Fix it.

```python
def rebuild(packets):
    pieces = {}
    for packet in packets:
        pieces[str(packet["number"])] = packet["data"]
    message = ""
    for number in sorted(pieces):
        message = message + pieces[number]
    return message
```

***Listing 29.8.** A rebuild with numbers as text. code/grade-8/05-how-the-internet-works/exercises/rebuild_bug.py*

**Solution of Exercise 29.5.**

`sorted` puts texts in the order of a [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary), [character](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string) by [character](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string): `"10"` and `"11"` start with `1`, so they come right after `"1"` and before `"2"`. The pieces 10 and 11, `k` and `l`, land after `b`. Keeping the numbers as numbers sorts them by [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value):

```python
def rebuild(packets):
    pieces = {}
    for packet in packets:
        pieces[packet["number"]] = packet["data"]       # numbers stay numbers
    message = ""
    for number in sorted(pieces):
        message = message + pieces[number]
    return message
```

*Numbers kept as numbers. code/grade-8/05-how-the-internet-works/exercises/rebuild_fixed.py*

**Exercise 29.6 ★★.**

This [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) accepts `"192.168.300.1"`. (`isdigit()` is true when a [string](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string) is made of digits only.) What is wrong with that address? Add the missing check.

```python
def is_valid(address):
    """True when address is four whole numbers separated by dots."""
    parts = address.split(".")
    if len(parts) != 4:
        return False
    for part in parts:
        if not part.isdigit():
            return False
    return True
```

***Listing 29.9.** A check that misses something. code/grade-8/05-how-the-internet-works/exercises/valid_bug.py*

**Solution of Exercise 29.6.**

Each part is one [byte](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte), so it cannot be above 255, and 300 is. The fix adds that check:

```python
def is_valid(address):
    """True when address is four numbers from 0 to 255 separated by dots."""
    parts = address.split(".")
    if len(parts) != 4:
        return False
    for part in parts:
        if not part.isdigit() or int(part) > 255:
            return False
    return True
```

*Each part from 0 to 255. code/grade-8/05-how-the-internet-works/exercises/valid_fixed.py*

Python checks `not part.isdigit()` first, so `int(part)` is only reached when the part is made of digits.

**Exercise 29.7 ★★.**

In many homes, the machines of the local [network](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-network) share the first three [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) of their addresses. Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `same_network(a, b)` that tells whether two addresses do.

**Solution of Exercise 29.7.**

Compare the [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of the first three parts:

```python
def same_network(a, b):
    """True when the two addresses share their first three bytes."""
    return a.split(".")[:3] == b.split(".")[:3]
```

*The same first three [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte). code/grade-8/05-how-the-internet-works/exercises/same_network.py*

**Exercise 29.8 ★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `sending_time(size_bytes, rate)` that returns the time, in seconds, to send a [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) of `size_bytes` [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) at `rate` [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) per second. How long does a 5-megabyte [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) take at 20 megabits per second?

**Solution of Exercise 29.8.**

```python
def sending_time(size_bytes, rate):
    """Seconds to send size_bytes bytes at rate bits per second."""
    return size_bytes * 8 / rate
```

*[Bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) to [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit), divided by the [bit rate](#def-g8-how-the-internet-works-bit-rate). code/grade-8/05-how-the-internet-works/exercises/sending_time.py*

$5{,}000{,}000 \times 8 = 40{,}000{,}000$ [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) at 20,000,000 [bits](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) per second: 2 seconds.

**Exercise 29.9 ★★.**

How many different addresses of four [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) are there? Write the number in full.

**Solution of Exercise 29.9.**

$2^{32} = 4{,}294{,}967{,}296$, a little more than four billion.

**Exercise 29.10 ★★★.**

How long does light take to cross 6,000 kilometres of glass fibre, in milliseconds? Use the speed of the weekend problem’s [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program).

**Solution of Exercise 29.10.**

The speed is $300{,}000 / 1.468 \approx 204{,}360$ kilometres per second, so $6{,}000 / 204{,}360 \approx 0.029$ seconds: about 29 milliseconds.

**Exercise 29.11 ★★★.**

A [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) of 1,000,000 [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) is sent in [packets](#def-g8-how-the-internet-works-packet) of 1,500 [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte), 40 of which are header. How many [packets](#def-g8-how-the-internet-works-packet) are needed, and how many [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) are sent in all?

**Solution of Exercise 29.11.**

Each [packet](#def-g8-how-the-internet-works-packet) carries $1{,}500 - 40 = 1{,}460$ [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) of the [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file). $1{,}000{,}000 / 1{,}460 \approx 684.9$, so 685 [packets](#def-g8-how-the-internet-works-packet), the last one not full. They carry $685 \times 40 = 27{,}400$ [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) of header, so $1{,}027{,}400$ [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) are sent in all.

**Exercise 29.12 ★★★.**

[Packets](#def-g8-how-the-internet-works-packet) may arrive twice. Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `reassemble(packets, count)` that rebuilds a message of `count` [packets](#def-g8-how-the-internet-works-packet), keeps one copy of each number, and also returns the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of the numbers that are missing.

**Solution of Exercise 29.12.**

A [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary) keeps one [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) per key, so a second copy of a piece simply replaces the first:

```python
def reassemble(packets, count):
    """Rebuild a message from packets that may come twice; list the missing numbers."""
    pieces = {}
    for packet in packets:
        pieces[packet["number"]] = packet["data"]    # a copy replaces the same piece
    message = ""
    missing = []
    for number in range(count):
        if number in pieces:
            message = message + pieces[number]
        else:
            missing.append(number)
    return message, missing
```

*Rebuilding with copies and gaps. code/grade-8/05-how-the-internet-works/exercises/reassemble.py*

## 29.8 Problem: A Photo to the Other Side of the World

**Problem 29.1.**

Weekend problem — a photo to the other side of the world

Sami’s photo weighs 3 [megabytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-units), 3,000,000 [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte). It goes to his cousin 20,000 kilometres away, half way round the Earth.

**Part I — Packets.**

A [packet](#def-g8-how-the-internet-works-packet) on most [networks](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-network) holds at most 1,500 [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte), and at least 40 of them are headers: 20 for the address part and 20 for the part that numbers the pieces.

1. How many [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) of the photo fit in one [packet](#def-g8-how-the-internet-works-packet) ?
2. How many [packets](#def-g8-how-the-internet-works-packet) does the photo need? Is the last one full?
3. How many [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) of header are sent, and what fraction of the whole is that?

**Part II — The program.**

For the speed of light in a fibre, the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) uses a figure from a fibre maker’s data sheet: light in its fibre is 1.468 times slower than in empty space, where it covers 300,000 kilometres per second.

```python
photo = 3_000_000                  # bytes
packet = 1_500                     # bytes in a packet, header included
header = 40                        # bytes of header in each packet
data = packet - header             # bytes of the photo in each packet

packets = photo // data
if photo % data != 0:
    packets = packets + 1          # one more packet for the end of the photo
total = photo + packets * header
print(packets, "packets,", packets * header, "bytes of headers,", total, "bytes in all")

speed = 300_000 / 1.468            # km per second in a glass fibre
propagation = 20_000 / speed
print(f"propagation over 20,000 km: {propagation:.3f} s")

for rate in [10_000_000, 100_000_000, 1_000_000_000]:
    sending = total * 8 / rate
    print(f"{rate // 1_000_000:>5} Mbit/s: sending {sending:.3f} s,"
          f" in all {sending + propagation:.3f} s")
```

***Listing 29.10.** The trip of the photo. code/grade-8/05-how-the-internet-works/listings/photo_trip.py*

4. What do lines 6 to 8 compute, and why the `if` ?
5. Run the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) . What is the propagation time over 20,000 kilometres?
6. What is the sending time at 10 megabits per second? At 100?
7. Why does the sending time use `total` , not `photo` ?

**Part III — What matters.**

8. At 10 megabits per second, which part of the time is larger, sending or propagation?
9. What does a ten times faster connection change, from 10 to 100 megabits per second? And from 100 to 1,000?
10. Can any connection bring the photo in less than 0.098 seconds? Why?
11. The [routers](#def-g8-how-the-internet-works-router) on the way add a little delay each. Does that change the answer to the previous question?
12. State the result.

**Solution of Problem 29.1.**

**1.** $1{,}500 - 40 = 1{,}460$ [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte).

**2.** $3{,}000{,}000 / 1{,}460 \approx 2{,}054.8$: 2,054 full [packets](#def-g8-how-the-internet-works-packet) carry $2{,}998{,}840$ [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte), and a 2,055th carries the last 1,160 [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte). It is not full.

**3.** $2{,}055 \times 40 = 82{,}200$ [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) of header, out of $3{,}082{,}200$ [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) in all: about 2.7 %.

**4.** The number of [packets](#def-g8-how-the-internet-works-packet): the whole number of full [packets](#def-g8-how-the-internet-works-packet), plus one if some [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) are left over. Without the `if`, the end of the photo would be lost.

**5.** 0.098 seconds, about a tenth of a second:

```
$ python photo_trip.py
2055 packets, 82200 bytes of headers, 3082200 bytes in all
propagation over 20,000 km: 0.098 s
   10 Mbit/s: sending 2.466 s, in all 2.564 s
  100 Mbit/s: sending 0.247 s, in all 0.344 s
 1000 Mbit/s: sending 0.025 s, in all 0.123 s
```

***Output 29.8.** The trip of the photo.*

**6.** 2.466 seconds at 10 megabits per second, 0.247 at 100.

**7.** The headers travel too: every [byte](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) sent takes time, not only the [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) of the photo.

**8.** Sending: 2.466 seconds against 0.098, twenty-five times more.

**9.** From 10 to 100 megabits per second, the whole trip goes from 2.564 to 0.344 seconds, more than seven times faster. From 100 to 1,000, it only goes from 0.344 to 0.123 seconds: the sending time shrinks, but the 0.098 seconds of propagation stay.

**10.** No. Even with an endless [bit rate](#def-g8-how-the-internet-works-bit-rate), the first [bit](https://one-course.com/books/computer-science/1/en/chapter/11-bits-and-bytes-counting-in-binary#def-g5-bits-and-bytes-bit) needs 0.098 seconds to cover 20,000 kilometres of fibre: nothing travels in a fibre faster than its light.

**11.** The [routers](#def-g8-how-the-internet-works-router) only add time, so the answer stays no; the real trip is a little longer than 0.098 seconds.

**12.** **Result.** The photo travels in 2,055 [packets](#def-g8-how-the-internet-works-packet), with 82,200 [bytes](https://one-course.com/books/computer-science/1/en/chapter/8-memory-and-storage#def-g4-memory-and-storage-byte) of headers. Crossing 20,000 kilometres of fibre takes 0.098 seconds whatever the connection, against 2.466 seconds of sending at 10 megabits per second and 0.247 at 100: past a certain speed, only the distance matters.
