Show contents
Chapter 2 of 7 · 20 min
Packets and protocols
By the end of this chapter, you'll be able to
- Describe the Internet's layered model and the principle of encapsulation
- Explain the role of ports and recognise the most common ones
- Compare TCP and UDP, and say when to use each
- Simulate cutting a message into packets and putting it back together
Layers that fit together
To send a message, each layer adds its own information, in a header, around what the layer above gives it. This is encapsulation, like a letter slipped into an envelope, itself put into a mail bag. The Internet's model has four layers:
| Layer | Role | Examples |
|---|---|---|
| Application | what the program wants | HTTP (web), DNS (names), SMTP (email) |
| Transport | connect two programs, make it reliable | TCP, UDP |
| Internet | route from machine to machine | IP |
| Network access | transmit over the physical medium | Wi-Fi, Ethernet, 4G/5G, fibre |
On arrival, each layer removes its header, until the request is handed to the web server.
Text description of the animation
- The browser prepares its request, in HTTP.
- TCP adds the source and destination ports, and a sequence number.
- IP adds the start and end addresses: it is a packet.
- The Wi-Fi card wraps it for the physical trip to the home router.
- On arrival, each layer removes its header, until the request is handed to the web server.
Ports: which application?
The IP address identifies a machine. But a machine runs several programs: browser, messaging, updates… The port, a number from 0 to 65,535, identifies the receiving program. An IP address plus a port therefore identifies one end of a communication. Services have conventional ports:
ports = {80: "HTTP (unencrypted web)", 443: "HTTPS (encrypted web)", 53: "DNS (domain names)",
22: "SSH (remote administration)", 25: "SMTP (sending email)"}
for port, service in sorted(ports.items()):
print(f"{port:>4}: {service}")
22: SSH (remote administration)
25: SMTP (sending email)
53: DNS (domain names)
80: HTTP (unencrypted web)
443: HTTPS (encrypted web)
The browser, on the client side, uses a randomly chosen port for each connection, for example 51234: this is what lets you open several tabs to the same site without mixing up the answers.
TCP and UDP
The transport layer offers two main protocols:
- TCP sets up a connection, numbers every packet, asks for acknowledgements, resends what is lost and puts everything back in order. Reliable, but you have to wait. It is the choice for the web, email, file transfers;
- UDP sends packets without any guarantee or acknowledgement. Faster and lighter, but a lost packet stays lost. It is the choice for video calls, online games, DNS: better a slightly degraded image than a conversation frozen while waiting for an old packet.
Let's simulate what TCP does: cut up a message, send it over a network that shuffles and loses packets, resend the missing ones, then reassemble.
import random
random.seed(3)
message = "Packet number 4 may well arrive before number 2."
size = 8
packets = [(n, message[i:i + size]) for n, i in enumerate(range(0, len(message), size))]
print(len(packets), "packets to send")
received = {}
round_ = 0
while len(received) < len(packets):
round_ += 1
to_send = [p for p in packets if p[0] not in received]
random.shuffle(to_send)
for number, content in to_send:
if random.random() < 0.3:
continue
received[number] = content
print(f"round {round_}: {len(received)}/{len(packets)} received")
print("".join(received[n] for n in sorted(received)))
6 packets to send
round 1: 2/6 received
round 2: 4/6 received
round 3: 6/6 received
Packet number 4 may well arrive before number 2.
- each packet carries a sequence number (
n); random.shufflesimulates out-of-order arrival, andrandom.random() < 0.3a 30% packet loss (a very bad network, for the example);- as long as packets are missing, the sender resends those not received: this is retransmission;
- the receiver sorts the pieces by number before reassembling them.
Mini-lab: a more or less reliable networkPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: how many packets?
On a typical Ethernet or Wi-Fi network, an IP packet is at most 1,500 bytes, including 40 bytes of IP and TCP headers. How many packets are needed to send a 3 MB photo (3,000,000 bytes)? And what share of the total traffic do the headers represent, as a percentage rounded to 1 decimal place?
Hint 1
Hint 2
math.ceil rounds up to the next whole number: a last, partly filled packet still counts.Show the solution and common mistakes
import math
file_size = 3_000_000
packet_size = 1500
headers = 40
payload = packet_size - headers
count = math.ceil(file_size / payload)
total_headers = count * headers
share = total_headers / (file_size + total_headers) * 100
print(count, "packets")
print(f"headers: {total_headers} bytes, that is {share:.1f}% of the traffic")
2055 packets
headers: 82200 bytes, that is 2.7% of the traffic
Headers are only about 2.7% of the traffic with large packets. For very small messages (a few bytes, as with some connected sensors), they can on the contrary weigh more than the data itself.
Common mistakes:
- Dividing by 1,500 instead of 1,460: you forget that headers take up room in every packet.
- Using
//orround://forgets the last incomplete packet, androundcan round down.
Summary
- 1The Internet is organised in layers: application, transport, internet, network access.
- 2Each layer adds its header around the data: this is encapsulation.
- 3The IP address identifies the machine, the port identifies the program (443 for HTTPS, 53 for DNS…).
- 4TCP numbers, acknowledges, retransmits and reorders; UDP is faster but with no guarantee.
- 5Packets can get lost or arrive out of order: sequence numbers let you rebuild the message.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.