logo
Published on

Networking by Layer: How an App's Data Reaches the Other Side of the World

Authors
  • avatar
    Name
    seren-wib
    Twitter
Contents

This post follows a single "Hi" sent from a chat app on a laptop in Seoul to a friend's phone in São Paulo, on the other side of the world, in layer order. The post that follows the same thing in time order (steps 0 to 13) is The Full Path of One Web Request to the Server. That post answers "what happens when". This one answers "who does what". While studying lecture 5 (networking) of Introduction to Computer Systems (컴퓨터시스템개론), I found that writing in lecture order scattered the same layer across many sections, so I regrouped everything by layer.

0. At a glance

Think of a company sending documents overseas. The person in charge writes only the content. The admin team writes the receiving department on the envelope. The mail room attaches the other company's address. The carrier only moves it to the next logistics center. Each team fills in its own box and trusts the rest to others.

The sender goes down adding a header at each layer, and the receiver goes up checking and stripping one at each layer

From the left: the OSI 7 layers, the TCP/IP layers with their data units and addresses, the headers the sender adds, and what the receiver checks. The red dot is the data being sent.

The teams in the analogy are layers. Wrapping envelope inside envelope is encapsulation. Opening them one by one on the receiving side is decapsulation. The content writer is the application layer, the receiving department is the transport layer's port, the company address is the network layer's IP address, and the transport between logistics centers is the link layer and the physical layer.

How to read the diagram

  • Left two columns: which TCP/IP layer each OSI layer falls into. The lecture teaches TCP/IP as 4 layers (link includes physical), but this post splits the physical layer out and uses five slots.
  • Middle: the sender. Each layer treats whatever it got from above as plain data and puts its own header in front. The link layer also adds an FCS at the end for error detection.
  • Right: the receiver. From the bottom up, each layer checks "is this for me, and is it intact?", strips its header and passes the rest up.

Example scenario

I send "Hi" from a chat app on my laptop at home in Seoul (Wi-Fi) to a friend who lives in São Paulo. The chat app keeps a TLS-protected connection open to a chat server (chat.example.com) in a US data center, and my friend's phone (LTE) keeps a connection open to the same server. The message travels twice: once laptop → server, once server → friend's phone.

DeviceAddress (all reserved for documentation or shared use)
Laptop (private)192.168.0.20, source port 51000
Home router (LAN side)192.168.0.1 (default gateway)
Home router (public)203.0.113.5
Chat server198.51.100.10 : 443
Friend's phone (inside carrier)100.64.12.34 (behind CGNAT)
Friend's carrier NAT (public)192.0.2.77

The five layers in one table

LayerData unitAddressTypical devicesTypical protocolsWhat it cannot do alone
ApplicationMessageDomain name (URL)Hosts (servers, clients)HTTP, DNS, TLS, SSH, SMTP, DHCPActually deliver to the program on the other side
TransportSegment / datagramPort numberHosts (only at the end devices)TCP, UDP (QUIC runs on UDP)Find a path, hand off to another network
NetworkPacketIP addressRouters, home routers, L3 switchesIP, ICMP, OSPF and BGP (route information)Reliability, actually hand off to the next device
LinkFrameMAC addressSwitches, bridges, APs, NICsEthernet, Wi-Fi, ARP (ties IP to MAC)Send outside the same link
PhysicalBit (signal)NoneRepeaters, hubs, cables, modemsSignal specs per mediumKnow whose bits they are and where they end

Why split it up

In the words of the lecture slides, it is "organizing complex communication functions by role". In practice you get three things.

  • Swappable parts: whether the laptop uses Wi-Fi or wired Ethernet, and whether the friend's phone uses LTE, IP, TCP and HTTP above stay the same. When the link technology changes, you do not have to rewrite the application.
  • Peers talk only to the same layer: the sender's TCP talks to the receiver's TCP (sequence numbers, ACK), and the sender's IP talks to the IP of routers on the path (destination IP, TTL). Each header is read only by the same layer on the other side.
  • Trust only the layer right below: each layer uses only the service of the layer directly below it. TCP trusts only that "IP sends the packet somewhere", and IP trusts only that "the link hands the frame to the next device".

The textbook definitions of the OSI 7 layers and encapsulation are in my networking class notes.

1. Mapping the OSI 7 layers to TCP/IP

OSI is a reference model made by the International Organization for Standardization (ISO), and the real internet runs on TCP/IP. OSI is a framework for "how to think about dividing the functions", and TCP/IP is the set of protocols actually used that fits that framework.

OSITCP/IP (4 layers, lecture)This post (5 slots)What goes in this layer
7 ApplicationApplicationApplicationHTTP, DNS, SMTP, SSH
6 PresentationApplicationApplicationCharacter encoding (UTF-8), compression, encryption (part of TLS)
5 SessionApplicationApplicationKeeping connection state (TLS session, HTTP keep-alive, login session)
4 TransportTransportTransportTCP, UDP
3 NetworkNetwork (internet)NetworkIP, ICMP
2 Data linkLinkLinkFrames and MAC of Ethernet and Wi-Fi (802.11)
1 PhysicalLinkPhysicalCables, connectors, voltage, light, radio, bit encoding

2. Application layer

This is the person writing the letter. They decide what to say and in what format, but they do not know which road the post office takes. The application layer defines the format of messages and the order in which they are exchanged, and the protocol is the rulebook of that service.

  • Data unit: message. An HTTP request or response, a DNS query or answer, one email.
  • Address: domain name. It is a name for people, and DNS turns it into an IP address before it is handed to the layers below.
  • Devices: hosts at the ends (laptops, phones, servers). Routers in the middle do not open the application layer.

The message built in this example

Say the chat app keeps a WebSocket connection open to the server and sends messages as JSON.

{ "type": "send", "to": "friend-42", "text": "Hi" }
  1. The app turns this string into UTF-8 bytes (presentation layer work).
  2. It adds a WebSocket frame header.
  3. TLS encrypts it into a TLS record.
  4. It hands those bytes to the socket. From here on it is the transport layer.

WebSocket starts with one HTTP request (Upgrade: websocket), then keeps that TCP connection open so either side can send messages at any time. That open connection is also why the server can push "Hi" to the friend's phone first. If the phone app is closed, the server hands the notification to the OS vendor's push service (APNs, FCM).

URL

https://chat.example.com/rooms/7?since=100#latest

PartNameMeaning
httpsSchemeHow to access it. It sets the default port (https 443, http 80)
chat.example.comHostDomain name. DNS finds its IP
/rooms/7PathThe resource requested from the server. It may differ from the server's real file path
?since=100QueryExtra information passed to the server
#latestFragmentA position inside the document. It is not sent to the server

A domain name gets more specific from right to left. com is the top-level domain, example.com is the registered domain, and chat is a name under it. The dots in a domain name have nothing to do with the dots in an IP address.

HTTP

The request-response rules used by the web and most app APIs.

  • Request: method (GET read, POST submit, PUT replace, DELETE delete) + path + version, headers (Host, Cookie, Content-Type), body.
  • Response: status code + headers + body (HTML, JSON, images).
Status code rangeMeaningExamples
2xxSuccess200 OK
3xxElsewhere or further action301, 302, 304
4xxProblem with the client request401, 403, 404
5xxProblem processing on the server500, 502, 503
  • Stateless: HTTP itself does not remember earlier requests. Login state is kept by the browser attaching the cookie the server gave it to every request (the server uses the cookie value to find the session).
  • Versions: HTTP/1.1 sends requests one after another on a connection (reusing the connection with keep-alive), HTTP/2 sends many requests at once as streams over one TCP connection, and HTTP/3 uses QUIC over UDP instead of TCP.

TLS

This is putting the envelope in a safe and sending it so that only the recipient has the key. TLS, on top of a TCP connection, gives server authentication (certificates), confidentiality (encryption) and integrity (tamper detection). HTTPS = HTTP + TLS.

  • The TLS 1.3 handshake takes 1 RTT. ClientHello (supported ciphers, key exchange value, SNI) → ServerHello + certificate + signature + Finished → both sides compute the same session key. The key itself never goes over the network (ECDHE).
  • After that, application data is encrypted symmetrically with the session key. Routers, home routers and ISPs in the middle cannot read inside TLS records.
  • What it does not protect: whether the site's content is genuine. Phishing sites use HTTPS too. The step-by-step process is in TLS setup.

DNS

It is a phone book. Give it a name and it tells you the number, but it does not make the call for you. DNS (Domain Name System) is a distributed database that finds the records attached to a domain name. It is not a system that carries web pages or messages.

RecordContent
AIPv4 address
AAAAIPv6 address
CNAMEAlias for another name (often used to hook up a CDN)
MXServer that receives mail
NSAuthoritative DNS server for this domain
TXTArbitrary string (domain ownership checks, mail auth policy)

Lookup order:

  1. App → the OS stub resolver. It checks the browser cache, the OS cache and the hosts file first.
  2. If not found, it asks the recursive DNS resolver (the DNS server received via DHCP, usually the ISP or home router, or a public DNS). Usually UDP 53, TCP 53 for large answers. To encrypt it, DoT (TLS, 853) or DoH (HTTPS, 443).
  3. The resolver asks in turn on your behalf. Root server (".com is over there") → TLD server ("example.com is over there") → authoritative server ("the A record for chat.example.com is 198.51.100.10").
  4. The resolver caches the record for its TTL. The next person gets it right away.
  • One name can have several IPs, and it can return different IPs depending on where you ask from. This is used for load balancing, failover and picking a nearby CDN server.
  • There are 13 root server names, but far more actual servers around the world. They use anycast, advertising the same IP from many places, so the nearest one answers.
  • DNS itself is an application layer protocol, and its query packets go through the lower layers just the same. The time order is in DNS: name → IP.

DHCP

When the laptop first joins the home Wi-Fi, it knows neither its own IP, nor the gateway, nor the DNS server. DHCP hands these out automatically. Discover → Offer → Request → Ack, DORA for short.

Other application protocols

ProtocolWhat it doesPort (transport)Encryption
SSHRemote shell, running commands, tunnels22 (TCP)Yes
TelnetRemote shell (old way)23 (TCP)None, unfit for the internet
SMTPSending mail (app → server, server → server)25 server to server, 587 submission (TCP)Added with STARTTLS
IMAPReading server mail synced across several devices143, 993 TLS (TCP)993 is TLS
POP3Pulling server mail down to a device110, 995 TLS (TCP)995 is TLS
FTPFile transfer (separate control and data connections)21 control (TCP)None
SFTPFile transfer over an SSH channel22 (TCP)SSH encryption
DNSName lookup53 (UDP, TCP for large answers)Added with DoT and DoH
DHCPAutomatic address configuration67 and 68 (UDP)None

The steps by which an SSH connection opens are written up separately in Connecting over SSH.

Client-server and P2P

AspectClient-serverP2P
RelationshipThe requesting side and the providing side are separateParticipants both request and provide
ExamplesThe web, the chat server in this exampleBitTorrent, direct connections in video calls (WebRTC)
Hard partsScaling the server, handling failuresParticipants come and go at any time, getting through NAT

One reason the laptop goes through the server instead of sending straight to the friend's phone is NAT. Both are behind NAT, so neither can open a connection to the other first (section 5, NAT). Video call apps use STUN to learn their outside address and try a direct connection, and relay through a TURN server if that fails.

What the application layer cannot do alone

  • Actually deliver to the program on the other side: the application layer only knows "this message to chat.example.com". Making the bytes arrive in order with nothing missing is the transport layer's (TCP's) job.
  • Point to which program on the same computer: that is done by the port number, that is, the transport layer.
  • Find a path by name: routers do not know names. The app has to get the IP from DNS and pass it down so the network layer can find a path.

3. Between application and transport: socket, operating system, driver, NIC

A restaurant customer only hands an order slip in at the counter. They do not need to know how the kitchen runs or which road the delivery rider takes. For an application, that counter is the socket.

From send() down to the NIC, and from the NIC on the other side up to recv()

The sending host is on the left, the receiving host on the right. Above the dotted line is user space, the middle is the kernel, and the bottom is hardware.

The counter is the socket, the kitchen is the TCP/IP stack inside the operating system kernel, the staff member who hands packages to the rider is the device driver, and the delivery motorbike is the NIC.

Socket

  • It is the network communication interface the operating system provides. A program deals only with the socket and never touches the NIC or driver directly.
  • A socket is identified by five values, (protocol, my IP, my port, peer IP, peer port), the 5-tuple. On the laptop side it is (TCP, 192.168.0.20, 51000, 198.51.100.10, 443).
  • Client call order: socket() → connect() (the TCP handshake happens here) → send() / recv() → close().
  • Server call order: socket() → bind(443) → listen() → accept() (a new socket per connection) → recv() / send().

When sending

  1. The app calls send(). A system call switches from user mode to kernel mode.
  2. The kernel copies the bytes into the socket's send buffer. send() returning does not mean the peer received it. It only means the data went into the buffer.
  3. TCP cuts the buffer contents into segments no larger than the MSS, and keeps a copy until it gets an ACK.
  4. IP looks at the routing table, picks the outgoing interface and next hop, and adds the IP header.
  5. It finds the next hop's MAC in the ARP cache and builds the frame header.
  6. The device driver puts the frame on the transmit ring buffer (TX ring) and tells the NIC "there is something to send".
  7. The NIC reads the frame straight from memory by DMA and adds the FCS, and the PHY (the physical layer circuit) turns the bits into a signal and sends it out.

Modern NICs often take over checksum calculation (checksum offload) and even cutting large data into segments (TSO). The layer split is logical, and which chip actually does the work varies by implementation.

When receiving

  1. The NIC turns the signal into bits and checks that the destination MAC is its own (or broadcast) and that the FCS is correct.
  2. It writes the frame into the receive ring buffer (RX ring) by DMA and raises an interrupt. When packets pile up, interrupts are reduced and the driver collects them in batches (Linux NAPI).
  3. The driver hands the frame to the kernel, and the kernel passes it up, checking the Ethernet header → IP header → TCP header in turn.
  4. TCP finds the socket by its 5-tuple, puts things in order, sends an ACK, and puts the bytes into the socket's receive buffer.
  5. It wakes up the server process waiting in recv(). The process reads the bytes from the buffer.

Interrupts and DMA themselves are the same story as lecture 3 (I/O control) of Introduction to Computer Systems. The CPU does not move bytes one at a time. The device writes into memory directly and signals when it is done.

Inter-process communication on the same computer

Processes cannot read each other's memory directly. On the same computer they use shared memory, pipes and message passing provided by the OS. On different computers they use a socket, naming an IP and port, and send over the network. Even on the same computer you can use a socket on 127.0.0.1 (loopback), and then the packet never goes down to the NIC. It loops back inside the kernel.

4. Transport layer

This is splitting the contents of a parcel into several boxes, with the receiver putting them back together by number and asking again for any missing box. The transport layer connects a program on one end host to a program on the other. Routers in the middle do not process this layer.

Port numbers and multiplexing

Once you reach the apartment building's address (IP), the unit number (port) is what is left.

RangeNameExamples
0 to 1023Well-known ports22 SSH, 53 DNS, 80 HTTP, 443 HTTPS
1024 to 49151Registered ports3306 MySQL, 5432 PostgreSQL
49152 to 65535Dynamic (ephemeral) portsClient source ports
  • The client's source port is picked by the OS on the spot (ephemeral port). The Linux default range is 32768 to 60999, a little different from the IANA range.
  • Multiplexing: sending the data of many apps out through one IP. Demultiplexing: handing each received segment to the right socket by port (by the whole 5-tuple for TCP). Even with tens of thousands of clients on the server's single port 443, every 5-tuple is different, so nothing gets mixed up.

TCP connection: 3-way handshake

  1. Laptop → server: SYN (seq = x, options such as MSS and window scale)
  2. Server → laptop: SYN+ACK (seq = y, ack = x + 1)
  3. Laptop → server: ACK (ack = y + 1)

It does not lay down a wire. It creates state in both kernels saying "talking with this peer, sequence numbers start here". This costs 1 RTT, and TLS 1.3 costs 1 more RTT before the first message goes out. The textbook explanation is in three-way handshake process.

Sequence numbers, ACK, retransmission

TCP resending a lost segment and putting things in order before handing them to the app

B was dropped in a router queue on the way. Even after receiving C, D and E, the server cannot hand them to the app and just repeats "give me from byte 101" (ACK 101). The laptop sees three duplicate ACKs and resends B.

This is the same idea as the ARQ from the computer networks course. The difference is scope. Link layer ARQ covers one hop to the next device, while TCP covers end to end, from the laptop in Seoul to the server in the US.

Flow control and congestion control

Both mean "slow down sending", but for different reasons.

AspectFlow controlCongestion control
ProtectsThe receiver's receive bufferThe network in between (router queues)
SignalThe receive window the receiver writes in ACKsPacket loss, rising delay
KnobrwndThe congestion window the sender sets on its own
BehaviorWhen the buffer fills, shrink rwnd to say "stop sending"At first double cwnd every RTT (slow start), cut it sharply on loss

Closing the connection

FIN → ACK, FIN → ACK: each side announces "nothing more to send" on its own (4-way). The side that closes first waits in TIME_WAIT for twice the maximum segment lifetime (2MSL). This keeps late old segments from mixing into a new connection with the same 5-tuple.

UDP

This is writing only the address on an envelope and dropping it in a mailbox. No delivery confirmation, no order.

  • 8 B header: source port, destination port, length, checksum. That is all.
  • No connection setup, no ordering guarantee, no retransmission. In exchange, it keeps message boundaries. One datagram sent arrives as is in one recv() on the receiving side.
  • Where it is used: DNS queries (one question, one answer), DHCP, voice and video calls, games (stale position data is better thrown away), and QUIC.

TCP vs UDP, and QUIC

ComparisonTCPUDP
Connection setupRequired (3-way handshake)None
Delivery formByte streamIndependent datagrams
Ordering guaranteeYesNo
RetransmissionYesNo
Message boundariesNot keptKept
Flow and congestion controlYesNo (up to the app)
Header size20 B or more8 B
ExamplesWeb (HTTP/1.1, HTTP/2), SSH, mailDNS, real-time voice and video, games

QUIC is a protocol that implements sequence numbers, retransmission, congestion control and TLS 1.3 encryption itself on top of UDP. HTTP/3 uses it. TCP lives inside the OS kernel and is hard to change, and when one segment goes missing, every stream behind it waits (head-of-line blocking). QUIC retransmits per stream, finishes connection setup and encryption setup in one go, and can be updated together with the app. This choice is an extension of TCP vs UDP. Even on UDP, you can build reliability on top.

What the transport layer cannot do alone

  • Find a path: TCP only knows the peer's IP, not which routers to pass through from Seoul to the US. The network layer does that.
  • Negotiate with devices in the middle: TCP runs only at the two ends. Even if a router in the middle drops a packet, TCP only knows it as "no ACK is coming". This is the end-to-end principle. Do the complex work at the ends and keep the middle simple.
  • What it gives the layer above: on top of unreliable IP, it builds "in order, nothing missing" (TCP). Or just fast (UDP).

5. Network layer

This is the international postal system. It looks only at the recipient's address on the envelope and decides "which sorting center does this letter go to next". It does not check whether the letter arrived. The network layer moves packets across different networks to the destination host, and its protocol is IP alone.

IP addresses

IPv4 splits 32 bits into four groups of 8 bits and writes each as 0 to 255. The front network part says which network, and the back host part says which device inside it. The boundary is shown by a prefix length or a subnet mask. Both carry the same information.

PrefixSubnet maskHost bitsUsable hosts
/8255.0.0.02416,777,214
/16255.255.0.01665,534
/24255.255.255.08254
/25255.255.255.1287126

The host count is reduced by 2 because the address with the host part all 0s (the network address) and the one with all 1s (the broadcast address) cannot be given to devices. How to split them is in subnetting and subnet mask.

Checking whether it is the same network

Before sending a packet, the laptop first checks "is the peer on the same network as me?". It ANDs my IP and the peer's IP with the subnet mask and compares the network addresses.

Laptop   192.168.0.20  AND 255.255.255.0 = 192.168.0.0
Server   198.51.100.10 AND 255.255.255.0 = 198.51.100.0   → different → to the default gateway
  • If they match, it finds the peer's MAC with ARP and sends directly inside the LAN. No router involved.
  • If they differ, it sends to the default gateway (192.168.0.1). The destination IP stays the server, and only the frame's destination MAC is the gateway.
  • The IP address alone cannot decide it. 192.168.1.20 and 192.168.2.30 are on the same network with /16 and on different networks with /24.
The same LAN goes only as far as the switch, other networks go through the gateway (router)

To a PC on the same LAN, traffic passes only through the AP and switch. To another IP network, it goes through the gateway (router). Joining Wi-Fi and Ethernet (the AP) and joining IP networks (the router) are different jobs.

Private IP, public IP, NAT

  • Private IPv4: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16. Used inside homes, schools and companies, and another home may reuse the same addresses. Internet routers hold no routes to these addresses.
  • Public IPv4: addresses assigned so they never overlap across the whole internet. Having a public IP does not mean it can always be reached from outside (firewalls).
  • NAT (Network Address Translation): the home router rewriting the private source IP of outgoing packets to its public IP. Since several devices in the home share one public IP, it rewrites ports too (NAPT, PAT).
DirectionBefore (source)After (source)What stays in the translation table
Outbound192.168.0.20 : 51000203.0.113.5 : 4000140001 ↔ 192.168.0.20:51000, peer 198.51.100.10:443
InboundDestination 203.0.113.5 : 40001Destination 192.168.0.20 : 51000Reversed by looking up the table

IPv6

  • 128 bits. Written as eight groups of 16 bits in hexadecimal, separated by colons. Leading zeros are dropped, and one run of all-zero groups can be shortened to :: once. 2001:0db8:0000:0000:0000:0000:0000:0010 → 2001:db8::10.
  • Addresses are plentiful, so in principle NAT is not needed. Each device gets a public address, and the firewall blocks connections coming from outside.
  • The header is a fixed 40 B, has no header checksum (the link and transport layers already check), and routers do not fragment. The TTL is called Hop Limit.
  • It uses ICMPv6 Neighbor Discovery instead of ARP, and multicast instead of broadcast.
  • Today dual stack, running IPv4 and IPv6 together, is the norm. When DNS returns both A and AAAA, the OS picks. More detail is in IPv6.

The IP header and best-effort delivery

Picking only the IPv4 header fields that come up in this post gives the following. Without options it is 20 B.

FieldWhat it does
Version4 or 6
Total lengthHeader + data length
Identification, flags, offsetUsed to reassemble fragments. DF bit = do not fragment
TTLDecreases by 1 at each router, dropped at 0. Keeps packets from looping forever
ProtocolWho the upper layer is. 1 ICMP, 6 TCP, 17 UDP
Header checksumChecks the header only. Recomputed at every router because TTL changes
Source and destination IPEnd-to-end addresses

IP is best-effort delivery. It tries hard to send toward the destination, but it does not guarantee arrival, order or no duplicates. When a router queue fills, it just drops. TCP above does the recovery. The default TTL differs by OS (Linux and macOS 64, Windows 128).

MTU and fragmentation

  • Each link has a maximum size it can carry in one frame. For Ethernet it is 1500 B, and this is called the MTU.
  • TCP cuts data to the MSS or less from the start (usually 1500 − IP 20 − TCP 20 = 1460 B).
  • If there is a hop with a smaller MTU along the way (a VPN tunnel, PPPoE 1492 B), one of two things happens.

Router, default gateway, home router

Routing and forwarding

OSPF builds routes inside an AS, BGP between ASes, and the router picks the next hop by longest prefix match

On the left is routing, which builds route information. On the right is forwarding, which uses that table for each packet. The red line is the actual path to 198.51.100.10.

In navigation terms, downloading the map ahead of time and turning the wheel at an intersection after reading the sign are different jobs. The first is routing, the second is forwarding.

  • Routing (control plane): routers exchange route information to build and update routing tables. Slowly, in the background.
  • Forwarding (data plane): every time a packet arrives, look up the table by destination IP and pass it to the next hop. Router hardware does this at line rate.
  • longest prefix match: if several entries contain the destination IP, pick the one with the longest (most specific) prefix. In the diagram, 198.51.100.10 matches /0, /22 and /24, but /24 wins. If nothing matches, the default route (0.0.0.0/0) is used.
  • AS: a group of networks run by one organization under one policy. One ISP or one large cloud is each an AS and gets an AS number.
  • Inside an AS (IGP): OSPF is the typical one. Each router floods its link costs to the whole AS (link-state), and each computes the shortest paths with Dijkstra. The older RIP is a distance-vector protocol that only counts hops and works only up to 15 hops. The comparison is in RIP vs OSPF.
  • Between ASes (EGP): only BGP is used. It advertises AS paths such as "this prefix is reachable via AS 64497 → 64498" (path-vector). Policy comes before shortest path. For example, it prefers a partner it exchanges with for free (peering) over an upstream provider it pays (transit). BGP runs on TCP 179. A routing protocol, too, ends up exchanging messages over the lower layers like an application.
  • So a router does not compute the fastest path in real time every time. It just looks at a table built in advance, and because of policy that table may send traffic on a geographically roundabout path. How the table is organized is in routing table.

ICMP: ping and traceroute

ICMP is a helper protocol of IP. It rides inside IP packets (protocol number 1), but it is not a transport layer protocol. It is for network layer control and error reporting.

ICMP messageWhen
Echo Request / Replyping
Time ExceededWhen TTL hits 0 and the packet is dropped
Destination UnreachableNo route, port closed, and so on
Fragmentation Needed (Packet Too Big)DF set but larger than the MTU (PMTUD)
  • ping: sends an Echo Request and measures the time until the Reply (RTT). If a firewall blocks ICMP, there is no reply even when the server is up.
  • traceroute (tracert): sends with TTL 1, 2, 3 and so on. Each router where TTL hits 0 sends back Time Exceeded, so collecting those source IPs reveals the path. macOS and Linux use UDP as the probe by default, Windows uses ICMP Echo. Routers that do not reply show up as * * *.

Unicast, broadcast, multicast, anycast

MethodTargetExamples
UnicastOne specific hostEvery chat packet in this example
BroadcastEveryone on the same LAN (does not cross routers)ARP request, DHCP Discover
MulticastOnly hosts that joined the groupIPTV, IPv6 neighbor discovery
AnycastThe nearest of several places using the same addressRoot DNS, public DNS, CDN

What the network layer cannot do alone

  • Reliability: it does not know if a packet was dropped, delayed or reordered. TCP fills the gap.
  • Telling programs apart: IP only gets you to the host. Which program it is, is the port (transport layer).
  • Actually handing off to the next device: a router only decides "the next hop is 192.168.0.1". Finding that device's MAC (ARP), putting the packet in a frame and sending it onto the cable is the link and physical layers' work.

6. Between network and link: ARP

It is like announcing in an apartment complex "who lives in unit 302?" and that person raising a hand. You use it when you know the IP address (unit 302) but not the face (MAC) whose door you actually knock on.

ARP (Address Resolution Protocol) is the protocol that finds a MAC address from an IP address within the same LAN.

  1. The laptop checks its ARP cache. If it has the MAC of gateway 192.168.0.1, done.
  2. If not, it broadcasts an ARP request. Destination MAC FF:FF:FF:FF:FF:FF, content "who has 192.168.0.1?".
  3. The home router sends an ARP reply with its own MAC by unicast.
  4. The laptop stores it in the cache and removes it after a while.
At each router the IP packet stays the same and only the frame is rebuilt

Client → router A → router B → web server (Ethernet, no NAT). Every time the link changes, the frame's MACs are rebuilt, and the IP packet travels on unchanged except for a lower TTL.

7. Link layer

This is local delivery within the neighborhood. It is only responsible up to the next sorting center. At the next center a new waybill is attached. The link layer hands a frame to the neighboring device over one directly connected hop (a link).

MAC addresses and Ethernet frames

  • MAC address: 48 bits, six hex groups like 00:1A:2B:3C:4D:5E. The first 24 bits (OUI) are the manufacturer, the last 24 bits are a serial number. It is burned into the NIC but can be changed in software, and modern phones sometimes use a random MAC per Wi-Fi network.
  • IP and MAC cannot stand in for each other. IP is "where is the final destination", MAC is "who receives it on this link right now". The comparison is in MAC address.
Ethernet frame fieldSizeContent
Preamble + SFD8 BA 1010… pattern that syncs the receiver's clock and marks the start (physical side)
Destination MAC6 BThe receiving NIC (a switch picks the port by this alone)
Source MAC6 BThe sending NIC (a switch learns locations from this)
EtherType2 BWhat is inside. 0x0800 IPv4, 0x86DD IPv6, 0x0806 ARP
Payload46 to 1500 BThe IP packet. Padded up to 46 B if short
FCS4 BCRC-32 error detection

If the FCS does not match, the frame is silently dropped. Ethernet does not resend. TCP does the retransmission. The CRC calculation is in CRC, and the general structure of a frame and FCS is in HDLC frame structure.

Switches and bridges

A switch learning locations from source MACs and picking ports by destination MAC

When a frame PC A sent to the server comes in on port 1, the switch learns "PC A = port 1" and sends it out only on port 3, where the server is.

  • Bridge: a device that joins two segments of a LAN. If the destination is on the same segment it does not forward, and it forwards only when the destination is on the other segment.
  • Switch: a bridge with many ports. Every time a frame comes in, it writes (source MAC, incoming port) into the MAC address table, looks up the destination MAC in the table and sends only out of that port.
  • A destination not in the table is sent out of every port except the incoming one (flooding). When the reply comes, the table fills in. Broadcast frames (FF:FF:FF:FF:FF:FF) also go out of every port except the incoming one.
  • When frames pile up for the same output port, they wait in a queue, and when the queue is full they are dropped. In modern wired LANs, loss comes from this congestion, not from collisions.
  • VLAN: logically splitting one switch into several LANs. Frames get a 4 B tag (802.1Q) to tell them apart. Traffic between VLANs has to go through a router (L3).
  • AP: a bridge that converts between wireless frames (802.11) and wired Ethernet frames. It is not a router. So traffic within the same LAN that only passes through an AP needs no router.

Shared media and medium access control

When several devices share one cable or one wireless channel, signals overlap if two devices talk at the same time. The rules that decide who talks when are Medium Access Control (MAC). The MAC in MAC address is this MAC.

  • CSMA/CD (Collision Detection): used in old shared-medium Ethernet (coaxial cable, hubs).
    1. Listen (carrier sense). If it is idle, send.
    2. Keep listening while sending, and if the signals overlap, treat it as a collision, stop, and send a jam signal.
    3. Wait a random time and send again. If collisions repeat, double the waiting range each time (binary exponential backoff).
  • Why do collisions happen if you checked before sending? Because a signal takes time to reach the end of the cable. If the other side already started but its signal has not reached me yet, I think the line is idle. The 64 B minimum Ethernet frame is also a length chosen "so a collision can be noticed while still sending".

Modern Ethernet: switches and full duplex

AspectShared-medium Ethernet (past)Switched Ethernet (modern)
ConnectionMany devices on one mediumA separate link from each device to the switch
CommunicationHalf duplexFull duplex
CollisionsHappenGenerally do not happen
Access controlCSMA/CDNot used
Main problemCollisionsSwitch output port congestion and queue loss

There are only two devices on a link (my NIC and the switch port), and the transmit and receive lines are separate, so sending and receiving at the same time do not overlap. That is why CSMA/CD is not needed.

Wi-Fi: CSMA/CA and RTS/CTS

Wireless is still a shared medium, and you cannot listen while sending. Your own transmit signal is so strong that you cannot hear others' weak signals. So instead of detecting collisions, it avoids them.

Hidden terminal problem: A and B cannot hear each other and collide at the AP

The dotted circles are how far each station's signal reaches. A and B both reach the AP but cannot hear each other. Even while A is sending, B judges the channel idle, and the two signals overlap at the AP.

How CSMA/CA (Collision Avoidance) works:

  1. Listen to see whether the channel is in use.
  2. If it is, wait until it is free.
  3. Even after it has been idle for a set time (DIFS), do not send right away. Wait a further random backoff. Even if several stations decide "idle" at once, their start times spread out.
  4. Send.
  5. After a short gap (SIFS), the AP sends a link layer ACK.
  6. If there is no ACK, treat it as a collision or error and resend. Unlike Ethernet, Wi-Fi retransmits at the link layer. Loss is common on wireless, so leaving it to TCP would be too slow.

RTS/CTS is an extra step that reduces the hidden terminal problem.

  1. A sends an RTS (may I send? + how long it will take) to the AP.
  2. The AP answers with a CTS (go ahead + how long it will take).
  3. Every station in the AP's range hears the CTS and stays quiet for that time (setting the NAV). B, which cannot hear A, can hear the AP, so it stops.
  4. A sends the data and the AP ACKs.
  • Limits: two extra frames add cost. So it is turned on only for large frames, or turned off. RTS frames can collide with each other too (but they are short, so the loss is small).
  • A Wi-Fi frame has up to 4 address fields (receiving wireless device, sending wireless device, final destination, original source). The AP turns these into the 2 addresses of an Ethernet frame and passes it to the wired side.
  • A Wi-Fi connection itself is only the laptop ↔ AP hop. Even if Wi-Fi is connected, the internet will not work if the ISP or server side is down.

The links one message passes through from the laptop in Seoul to the phone in São Paulo all use different technologies. The IP packet is the same, and only the frame carrying it changes on each link.

HopLink technologyAccess method
Laptop ↔ home routerWi-Fi (802.11)CSMA/CA, link ACK
Home router ↔ carrierFiber access network (FTTH, PON)Downstream is broadcast to all and each decrypts only its own, upstream gets time slots assigned by the OLT (TDMA)
Carrier internal, backbone, undersea hopsEthernet over optical fiber (point-to-point)Full duplex, no access control
Friend's phone ↔ base stationLTE / 5GThe base station assigns time and frequency resources to each device (scheduling). No CSMA
Other access methodsDSL (phone line), cable internetReuse existing phone and cable TV lines

Mobile networks do not "listen and send when idle" like Wi-Fi. The base station tells each device "you, at this time, on this frequency". That is why hundreds of devices on one base station can share it without collisions.

Network scope and topology

Network scope: PAN, LAN, MAN, WAN

PAN (around the body, Bluetooth), LAN (home, building), MAN (city), WAN (country, continent). As the scope grows, the link technology and the operator change.

Topologies: bus, star, tree, mesh

The shape in which devices and connections are laid out. Modern LANs are stars and trees with a switch in the middle, and the internet backbone is closer to a mesh with many paths.

Topology is viewed in two ways: physical (how the cables are actually laid) and logical (how data flows). Star wiring tied together by a hub is physically a star but logically works like a bus, with everyone sharing the same medium.

  • Send outside the link: a MAC only works within the same link. To go to another network you need IP and routers. Each time it passes a router, the frame is rebuilt.
  • End-to-end reliability: it only goes as far as dropping corrupted frames by FCS (Wi-Fi retransmits only within that link). The whole way from Seoul to the US is TCP's job.
  • Turn bits into signals: turning a frame into voltage, light or radio is the physical layer.

8. Physical layer

This is turning letters into Morse code and blinking a flashlight. It does not know who is writing to whom. It only blinks 0s and 1s at a set beat. The physical layer turns bits into signals on the medium and reads them back as bits.

The same 8 bits sent as copper wire voltage, fiber light and radio

From the top: bits, NRZ (voltage high and low), Manchester (a rise or fall in the middle of each bit), light on and off, and radio phase. The red line is the position of the bit being sent now.

Morse code is encoding and modulation, the flashlight is the transmitter (the NIC's PHY, a laser, an antenna), and the beat is the bit time (clock).

  • Data unit: bit. In practice, one symbol (a single piece of signal) carries several bits.
  • Address: none.
  • Devices: repeaters, hubs, cables, connectors, modems, ONTs, optical transceivers, antennas.

Media

MediumSignalCharacteristicsWhere it is used
Twisted pairVoltageCheap and easy to handle, about 100 m, twisting cancels noiseEthernet inside buildings
Coaxial cableVoltageGood shieldingCable TV and internet, old Ethernet
Optical fiberLightHigh bandwidth and low attenuation, tens of km without repeaters, no electromagnetic noiseAccess networks, backbone, submarine cables
Wireless (radio)RadioMobility, but a shared medium with heavy noise, attenuation and interferenceWi-Fi, LTE/5G, Bluetooth

The detailed characteristics of each medium are in Twisted Pair, Coaxial Cable and Optical Fiber. Attenuation, the weakening of a signal over distance, is in Attenuation.

Bits into signals

  • Even for the same 0101, both sides must agree in advance on the shape of the signal.
  • NRZ: 1 is high voltage, 0 is low voltage. Simple, but when 0s or 1s run long, the signal does not change and the receiver loses the beat.
  • Manchester: the signal always changes in the middle of each bit (rising is 1, falling is 0, per 802.3). Since it changes every bit, the receiver resyncs its clock there. 10 Mbps Ethernet (10BASE-T) used it. In exchange, the signal changes twice as often and uses more bandwidth.
  • Fast links put several bits in one symbol. Gigabit Ethernet (1000BASE-T) sends 5-level voltages (PAM-5) on 4 twisted pairs at once, and Wi-Fi splits the frequency finely with OFDM and uses QAM (a combination of amplitude and phase) on each.
  • The comparison of encoding schemes is in NRZ family and Manchester.

Multiplexing

Ways for several signals to share one link.

  • FDM: split by frequency. Wi-Fi channels, radio stations.
  • TDM: split by time. PON upstream, the old telephone network.
  • WDM: send dozens of lights with different wavelengths (colors) together on one strand of fiber. This is why submarine cables have such large capacity. Details are in WDM.

Full duplex, half duplex, simplex

MethodMeaningExamples
SimplexOne direction onlyBroadcasting
Half duplexBoth directions, but only one side at a timeWalkie-talkies, one Wi-Fi channel, hub Ethernet
Full duplexBoth sides at the same timeTelephone, switched Ethernet, two fiber strands

Wi-Fi is half duplex because only one device can talk on a channel at a time. That is why the CSMA/CA above is needed. My notes are in transmission direction.

Bandwidth, throughput, latency

ConceptMeaningUnitAnalogy
BandwidthTheoretical maximum transfer ratebpsNumber of lanes
ThroughputTransfer rate actually achievedbpsNumber of cars that actually passed
LatencyTime from departure to arrivalmsTravel time
JitterHow uneven the arrival intervals aremsBuses arriving at uneven intervals
Packet lossShare of what was sent that never arrived%Parcels that vanished on the way

Throughput is lower than bandwidth. Congestion, control information such as headers, loss and retransmission, device performance and processing speed at both ends all cut into it. The theoretical maximum a link can reach is set by bandwidth and signal-to-noise ratio (Channel Capacity). Video downloads care about throughput, while video calls and games care about latency, jitter and loss.

Physical layer devices

How far up each device opens: repeater, switch, router

A repeater only amplifies the signal at the physical layer, a switch opens up to the MAC at the link layer, and a router opens up to the IP at the network layer. Only hosts use all four layers.

What the physical layer cannot do alone

  • Where something starts and ends: bits just keep coming. Frame boundaries are set by the link layer with the preamble and length.
  • Whose it is: there is no address. A hub sprays to everyone. Filtering is done by the link layer (the NIC's MAC check, switches).
  • Fix errors: it does not know when noise flips a bit. The link layer's FCS finds it, and an upper layer resends.

9. To the other side of the world: the real structure of the internet

The internet is not one network but a network of networks. No single company owns it all. Tens of thousands of organizations each run their own part and connect to one another. The common rules used at those seams are IP and BGP.

The networks a message passes through from the laptop in Seoul to the friend's phone in São Paulo

This shows one possible path. The box color is the highest layer that device works at. Distances are rough estimates, not a measured path.

Access network

The first stretch that connects a user's device to the ISP. The lecture slides divide the path into user-side network → access network → ISP network → backbone → server network.

ISP, AS, IXP

  • ISP (Internet Service Provider): a business that sells internet access. Each ISP is usually one or more ASes.
  • Three ways ISPs connect to each other:
    1. Private peering: two providers plug a line directly into each other.
    2. Transit: pay an upstream provider to buy "a path to the whole internet".
    3. IXP (Internet Exchange Point): many providers gather at a large Ethernet switch in one building, set up BGP sessions with each other and exchange traffic. The IXP itself is link layer equipment (a switch fabric), and path decisions are made by each provider's routers with BGP.
  • Tier 1: top-level providers that can reach every part of the internet without paying (through peering with each other alone). Providers below them buy transit from Tier 1 or from providers below Tier 1.
  • Which providers a packet passes through is decided by each AS's BGP policy. It may not be the geographically shortest path.

Backbone and submarine cables

  • Backbone: high-capacity core links connecting regions, countries and continents. Made of optical links of hundreds of Gbps to Tbps and large routers.
  • Submarine cables: most international traffic between continents goes over optical cables under the sea. Satellites carry only a part.
    • A cable holds a few fiber pairs, and each strand carries dozens of wavelengths with WDM.
    • Every few tens of km on the sea floor there is an optical repeater that amplifies the weakened light. It is a physical layer device. Power is sent from land through a copper conductor inside the cable.
    • Where a cable reaches land is a landing station, and from there it connects to land backbones and routers.
    • Routes differ by region, and new cables get laid or old ones replaced. You can see a map at submarinecablemap.com.
  • Seoul to São Paulo is about 18,000 km by great-circle distance (estimate, not measured). There is no direct cable, so traffic usually crosses the Pacific through the US or goes around via other continents.

Data centers, load balancers, CDN

  • Servers sit in data centers. Incoming packets go through the data center router → firewall → load balancer to one of many servers. An L4 load balancer looks only at IP and port, and an L7 load balancer terminates TLS and looks at the HTTP path too.
  • The cloud is not an abstract space either. It is the real computers in data centers like these. Clusters (computers in one place acting as one) and grids (connecting resources of many institutions) also end up exchanging messages over this network.
  • CDN (Content Delivery Network): copies images, video and files to servers near the user (the edge) and serves them from there. DNS returns a nearby edge IP (region-based answers), or the same IP is advertised from many places (anycast), to send users to a nearby one. "Nearby" means by network path, load and policy, not geography.
  • The chat message itself cannot be put on a CDN. It is data created in real time. But attachments such as a photo the friend sent can be fetched from a CDN. Video streaming uses CDN + adaptive quality selection together.

To the friend's phone: once more from the server

  1. The chat server unwraps the received "Hi" through TLS and WebSocket, reads it, and finds the recipient's connection.
  2. It builds a new message and sends it over the TCP connection the friend's phone keeps open. This is a new encapsulation. The packet from the laptop does not go on as is.
  3. The destination IP is 192.0.2.77, the public address of the friend's carrier NAT, and the port is the number that NAT assigned to the friend's phone connection. The friend's phone opened the connection first, so there is an entry in the CGNAT translation table.
  4. US → Brazil (land fiber, submarine cable, Brazilian ISP) → carrier core network → CGNAT turns the destination back into 100.64.12.34 → base station.
  5. The base station assigns radio resources to the friend's phone and sends the frame. The phone's NIC (modem) → driver → kernel TCP/IP → socket → chat app. The app shows "Hi" on the screen.

Where delay comes from

Four kinds add up at every hop.

DelayCauseWhat sets its size
Processing delayHeader checks, FCS and checksums, table lookupsDevice performance (µs per router)
Queuing delayWaiting in the buffer until earlier packets leaveTraffic at that moment. Different every time
Transmission delayTime to push all the frame's bits onto the linkFrame length ÷ link speed
Propagation delayTime for the signal to travel along the mediumDistance ÷ signal speed
  • Propagation delay cannot be reduced by upgrades. Light in fiber travels at about 2/3 of its speed in a vacuum, about 200,000 km per second. A path of about 20,000 km takes about 100 ms one way (calculated, not measured). So the RTT to the other side of the world has a floor of several hundred ms, and the only way to lower that floor is to put servers closer (CDN, regional servers).
  • Transmission delay shrinks as the link gets faster. A 1500 B frame takes 12 µs on a 1 Gbps link and 1.2 ms on 10 Mbps (calculated).
  • Queuing delay differs per packet, which creates jitter, and when the queue overflows it becomes loss. This is exactly the signal TCP congestion control watches.
  • On top of this comes processing at both ends (waiting for the server's response, app processing, TCP and TLS handshake round trips). On a first connection, TCP 1 RTT + TLS 1 RTT pass before the first message goes out, so to the other side of the world that alone adds several hundred ms. This is why a chat app that keeps its connection open feels fast.
  • A packet-switched network shares links among many users. Even to the same server, delay and throughput vary from moment to moment. The comparison with circuit switching is in Packet Switching.

10. Everything that crosses layers, at once

Encapsulation and decapsulation

LayerWhat the sender addsIn this exampleWhat the receiver checks
ApplicationMessage, TLS recordChat JSON → WebSocket → TLSDecryption, parsing the message
TransportSource and destination ports, seq, ack, window, checksum51000 → 443Find the socket by 5-tuple, reorder, ACK
NetworkSource and destination IP, TTL, protocol number, header checksum192.168.0.20 → 198.51.100.10, TTL 64, 6Whether the destination IP is mine, protocol number
LinkSource and destination MAC, EtherType, FCSLaptop MAC → home router MAC, 0x0800Whether the destination MAC is mine, FCS
PhysicalPreamble, encoded signalWi-Fi radioSignal → bits, clock sync

How far each device opens

DeviceLayers it opensWhat it does
Repeater, hub, optical repeaterPhysicalRe-amplify the signal or copy it to everyone
Switch, bridge, APLinkPick a port by MAC, convert wireless ↔ wired frames
RouterNetworkNext hop by IP, TTL − 1, new frame
NAT router, firewallNetwork + transportRewrite and inspect IPs and ports
L7 load balancer, proxyUp to applicationTerminate TLS, look at HTTP and pick a server
Host (laptop, server)AllEncapsulation and decapsulation
HeaderChanges on each linkStays the same end to end
LinkSource and destination MAC, frame type (Wi-Fi ↔ Ethernet)
IPTTL (−1 per hop), header checksum, source IP at NATDestination IP (when there is no NAT on the server side)
TCPSource port at NATDestination port 443, seq, data
ApplicationContent encrypted with TLS (the middle cannot read it)

The same table for a web request is in What changes on each link vs what stays.

Protocols that tie layers together

ProtocolIts own layerCarried inWhat it connects
DNSApplicationUDP/TCP 53Application names → network IPs
DHCPApplicationUDP 67/68Network layer settings (IP, mask, gateway, DNS)
ARPBetween link and networkDirectly in Ethernet framesNetwork IP → link MAC
NATA function of network devicesRewrites IP and TCP/UDP headersPrivate address ↔ public address (including ports)
ICMPNetworkIP (protocol 1)Reports errors during IP delivery to the source, ping and traceroute
BGPBehaves like an applicationTCP 179Route information between ASes → network layer routing tables
OSPFNetwork layer controlIP (protocol 89)Link costs inside an AS → routing tables
TLSApplication (OSI 5 to 6)TCPEncryption and authentication of application data

A VPN wraps this table once more. It encrypts the entire IP packet and puts it inside UDP, so you get a network layer stacked on top of another network layer. The process is in When using a VPN.

11. Numbers table

As of 2026-11-25. Only values set by specifications and calculated values are included. Nothing here was measured.

ItemValueSource or basis
IPv4 address / IPv6 address / MAC address32 / 128 / 48 bitsSpec
Port number16 bits (0 to 65535)Spec
TCP / UDP / IPv4 / IPv6 header20+ / 8 / 20+ / 40 BSpec (+ = grows with options)
Ethernet header + FCS14 + 4 B (preamble 8 B extra)Spec
Ethernet MTU / typical TCP MSS1500 / 1460 B1500 − 20 − 20
Default TTLLinux and macOS 64, Windows 128OS default settings
Speed of light in fiberAbout 200,000 km/sSpeed of light in vacuum ÷ refractive index of about 1.5
Seoul ↔ São Paulo great-circle distanceAbout 18,000 kmEstimate
One-way propagation delay over a 20,000 km pathAbout 100 msCalculated
Sending 1500 B at 1 Gbps / 10 Mbps12 µs / 1.2 msCalculated (12,000 bits ÷ link speed)