Skip to main content
Editor

How the Internet Works: Networks, Packets and Protocols

Beginner40 min3 exercises40 XP
0/3 exercises

When you open a video on your phone, the data cross dozens of devices owned by different companies, cut into small pieces that can each take their own route. It works because every one of those devices follows the same published rules. Here is how the pieces fit together, from your phone to a server and back.

What is a computer network?

A computing device is a physical object that can run a program. Phones, laptops, game consoles, servers, routers and smart thermostats are all computing devices.

A computing system is a group of computing devices and programs working together for a common purpose. Your school's online gradebook is one: teachers' laptops, the server that stores the grades, and the app on your phone all work together so you can see your scores.

A computer network is a group of interconnected computing devices that can send or receive data. A network is a type of computing system. The devices in your home that share one Wi-Fi router form a small network.

What is a path, and what is routing?

When one device (the sender) sends data to another (the receiver), the data rarely go straight there. They hop from device to device. A path is a sequence of directly connected devices that starts at the sender and ends at the receiver. Routing is the process of finding a path.

Below, a small network is stored as a dictionary: each device maps to the list of devices it is directly connected to. An ISP (Internet service provider) is the company that connects your home to the rest of the Internet.

A network as a dictionary of neighbours
network = {
"phone": ["home router"],
"home router": ["phone", "laptop", "ISP router"],
"laptop": ["home router"],
"ISP router": ["home router", "router B", "router C"],
"router B": ["ISP router", "router D"],
"router C": ["ISP router", "router D"],
"router D": ["router B", "router C", "video server"],
"video server": ["router D"],
}
for device, neighbours in network.items():
print(f"{device:<13} is directly connected to {', '.join(neighbours)}")
route_1 = ["phone", "home router", "ISP router", "router B", "router D", "video server"]
route_2 = ["phone", "home router", "ISP router", "router C", "router D", "video server"]
for route in [route_1, route_2]:
print(f"{len(route) - 1} hops: {' -> '.join(route)}")
Output
phone         is directly connected to home router
home router   is directly connected to phone, laptop, ISP router
laptop        is directly connected to home router
ISP router    is directly connected to home router, router B, router C
router B      is directly connected to ISP router, router D
router C      is directly connected to ISP router, router D
router D      is directly connected to router B, router C, video server
video server  is directly connected to router D
5 hops: phone -> home router -> ISP router -> router B -> router D -> video server
5 hops: phone -> home router -> ISP router -> router C -> router D -> video server

There are two paths from the phone to the video server, one through router B and one through router C. On the Internet, routing is usually dynamic: the path is not decided in advance. Each router picks the next hop based on conditions at that moment, such as which links are busy or broken, so two packets from the same video can travel different paths.

No single device holds a map of the whole Internet. A router knows its own neighbours and which of them leads toward each group of addresses, and routers keep telling each other about changes. Every hop moves the data a little closer, and together the hops form the path.

Exercise 1: Is It a Path?
Write Code

Write is_path(network, route). network is a dictionary that maps each device to the list of devices it is directly connected to, and route is a list of devices. Return True if route is a path: it has at least two devices (a sender and a receiver), and every device in it is directly connected to the next one. Otherwise return False.

net = {'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A', 'D'], 'D': ['B', 'C', 'E'], 'E': ['D']}
is_path(net, ['A', 'B', 'D', 'E'])  ->  True
is_path(net, ['A', 'D', 'E'])       ->  False   (A and D are not directly connected)
def is_path(network, route):
# Check every pair of neighbouring devices in the route
pass

What is bandwidth?

The bandwidth of a network is the maximum amount of data that can be sent in a fixed amount of time. It is usually measured in bits per second, most often in megabits per second (Mbps, millions of bits per second). Bandwidth works like the number of lanes on a highway: more lanes let more cars through each minute.

File sizes are usually given in bytes, and a byte is 8 bits, so to find a download time you first multiply by 8. Bandwidth is a maximum, so real downloads are often slower, for example when the whole family is streaming at once.

Download times at different bandwidths
files_mb = {"song": 4, "phone photo": 3, "TV episode": 900, "game update": 5000}
speeds_mbps = [10, 100, 1000] # megabits per second
def nice_time(seconds):
if seconds < 1:
return f"{seconds:.2f} s"
if seconds < 60:
return f"{seconds:.1f} s"
return f"{seconds / 60:.1f} min"
print(f"{'file':<12}" + "".join(f"{speed:>10} Mbps" for speed in speeds_mbps))
for name, megabytes in files_mb.items():
megabits = megabytes * 8 # 1 byte = 8 bits
times = [nice_time(megabits / speed) for speed in speeds_mbps]
print(f"{name:<12}" + "".join(f"{t:>15}" for t in times))
Output
file                10 Mbps       100 Mbps      1000 Mbps
song                  3.2 s         0.32 s         0.03 s
phone photo           2.4 s         0.24 s         0.02 s
TV episode         12.0 min        1.2 min          7.2 s
game update        66.7 min        6.7 min         40.0 s
Exercise 2: How Long Will It Take?
Write Code

Write transfer_seconds(megabytes, mbps). It returns the least time, in seconds, to send a file of megabytes megabytes over a connection with a bandwidth of mbps megabits per second, rounded to 1 decimal place.

transfer_seconds(100, 50)  ->  16.0   (100 MB is 800 megabits, and 800 / 50 = 16)
def transfer_seconds(megabytes, mbps):
# Turn bytes into bits first
pass

What makes the Internet different from other networks?

The Internet is a network made of many interconnected networks, such as home networks, school networks, phone carriers and huge company networks, all using standardized, open (nonproprietary) communication protocols.

A protocol is an agreed-upon set of rules that specify how a system behaves. Think of addressing an envelope: because everyone agrees where the address and stamp go, any post office in the world can handle your letter. Internet protocols say things like how an address is written, how big a piece of data can be, and what a device does when something goes wrong.

The Internet's protocols are open: they are published for anyone to read and use, and no company owns them. That makes it easy to connect new devices. A start-up that invents a new smart doorbell does not need permission from anyone; it builds the doorbell to follow the protocols, and it works.

Getting on the Internet depends on connecting your device to a device that is already connected, such as a Wi-Fi router, a cell tower or a school's network switch.

The scalability of a system is its capacity to change in size and scale to meet new demands. The Internet was designed to be scalable. The network that grew into it connected four computers in 1969; today the Internet connects billions of devices, and adding another network does not require redesigning the ones already there.

How does data travel in packets?

Information moves through the Internet as a data stream. The stream is cut into chunks, and each chunk is wrapped, or encapsulated, in a packet. A packet holds its chunk of data plus metadata: information used to route it from the origin to the destination (such as both addresses) and to put the data back together (such as the packet's number in the sequence).

A packet usually carries at most about 1,500 bytes of data, so one phone photo becomes about two thousand packets.

Why cut data up at all? Small packets let many people share the same links at once, the way many cars share a road, instead of one huge file blocking a link until it finishes. If a link fails or a packet is lost, only that small piece has to be sent again, and later packets can take another route around the problem.

Packets travel independently, so they may arrive in order, out of order, or not at all. The demo cuts a message into packets, then shuffles them and loses one, the way a real network sometimes does.

Cutting a message into packets
import random
message = "Meet at the library at 3:30 and bring your laptop!"
CHUNK = 8 # characters per packet
total = (len(message) + CHUNK - 1) // CHUNK # round up
packets = []
for start in range(0, len(message), CHUNK):
packets.append({
"from": "192.0.2.15", "to": "198.51.100.7", # metadata for routing
"seq": start // CHUNK + 1, "total": total, # metadata for reassembly
"data": message[start:start + CHUNK],
})
print(f"{total} packets. The first one:")
print(packets[0])
random.seed(4)
random.shuffle(packets) # packets take different routes...
arrived = packets[:-1] # ...and one of them is lost
print("Arrival order:", [p["seq"] for p in arrived])
Output
7 packets. The first one:
{'from': '192.0.2.15', 'to': '198.51.100.7', 'seq': 1, 'total': 7, 'data': 'Meet at '}
Arrival order: [6, 5, 7, 4, 1, 3]

The receiver uses the metadata to rebuild the message. Sorting by sequence number fixes the order, and a gap in the numbers shows which packet never came.

Reassembling the packets
by_seq = {p["seq"]: p["data"] for p in arrived}
missing = [n for n in range(1, total + 1) if n not in by_seq]
print("Missing packets:", missing)
rebuilt = "".join(by_seq.get(n, "[?]") for n in range(1, total + 1))
print("Rebuilt so far: ", rebuilt)
for n in missing: # the receiver asks for these again
start = (n - 1) * CHUNK
by_seq[n] = message[start:start + CHUNK]
print("After resending:", "".join(by_seq[n] for n in range(1, total + 1)))
Output
Missing packets: [2]
Rebuilt so far:  Meet at [?]ary at 3:30 and bring your laptop!
After resending: Meet at the library at 3:30 and bring your laptop!
Exercise 3: Reassemble a Message
Write Code

Write reassemble(packets, total). packets is a list of dictionaries with the keys "seq" (1 to total) and "data", in the order they arrived. Return the full message with the chunks in sequence order. If any packet from 1 to total is missing, return None. The same packet can arrive twice; use it once.

reassemble([{'seq': 2, 'data': 'lo!'}, {'seq': 1, 'data': 'Hel'}], 2)  ->  'Hello!'
def reassemble(packets, total):
# Use each packet's sequence number to put the data in order
pass

What do IP, TCP and UDP do?

IP, TCP and UDP are common protocols on the Internet. They usually work in layers, each handling one part of the job.

  • IP (Internet Protocol) handles addresses and routing. Every device on the Internet has an IP address, such as 192.0.2.15, and IP gets each packet from router to router toward the address on it.
  • TCP (Transmission Control Protocol) makes delivery reliable. It numbers the packets, puts them back in order, and asks for any missing ones to be sent again, which is what the reassembly demo did. Email, file downloads and most web pages travel over TCP, because a missing piece would break them.
  • UDP (User Datagram Protocol) sends packets without numbering them for reassembly or resending lost ones. That makes it faster, and it suits video calls and fast online games, where a late piece of data is useless anyway: it is better to skip a frame than to freeze while waiting for it.
  • Is the World Wide Web the same as the Internet?

    No. The World Wide Web is a system of linked pages, programs and files: everything you reach through links in a browser. HTTP (and its secure version, HTTPS) is the protocol the web uses: your browser sends an HTTP request asking for a page, and the server sends an HTTP response back.

    The web uses the Internet to move those requests and responses. HTTP messages are cut into packets and carried across the Internet's protocols, usually TCP and IP, like any other data. Plenty of what travels on the Internet is not the web at all, such as the email app on your phone, video calls and multiplayer games.

    A web address shows the layers. The program below splits one into its parts.

    What a web address tells the browser
    from urllib.parse import urlparse
    url = "https://pythoncompiler.io/python/exercises/"
    parts = urlparse(url)
    print("Protocol:", parts.scheme) # how to talk: the web's protocol, secured
    print("Server: ", parts.netloc) # which computer on the Internet
    print("Page: ", parts.path) # which file or page on that computer
    request = f"GET {parts.path} HTTP/1.1\nHost: {parts.netloc}"
    print("\nThe browser's request starts like this:")
    print(request)
    Output
    Protocol: https
    Server:   pythoncompiler.io
    Page:     /python/exercises/
    
    The browser's request starts like this:
    GET /python/exercises/ HTTP/1.1
    Host: pythoncompiler.io

    Check your understanding

    A small company invents a new kind of smart speaker. It connects to the Internet without the company asking any other organization for permission. Which of the following best explains why this is possible?

    Answers

    Which of the following are typically included in a packet's metadata? Select two answers.

    Select 2 answers.

    Answers

    Which of the following best describes the relationship between the Internet and the World Wide Web?

    Answers

    A network has a bandwidth of 50 megabits per second. What is the least amount of time it can take to send a 200-megabit file over this network?

    Answers

    In a network, these pairs of devices are directly connected: A and B, A and C, B and D, C and D, D and E. Which of the following is a path from A to E?

    Answers

    You load the same website twice, a minute apart, and the packets travel through different routers each time. Which of the following best explains this?

    Answers

    The Internet was designed to be scalable. What does this mean?

    Answers

    Exam topics: 4.1 The Internet (CSN-1.A, CSN-1.B, CSN-1.C, CSN-1.D)

    Related Tutorials

    Was this tutorial helpful?