Computer Networks

The Invisible
Mega-Structure

Computer Networks connect independent computers to share resources and data. From the fiber cables under the ocean to the Wi-Fi signals in the air.

It is a layered abstraction. Each layer solves a specific problem—converting signals to bits, bits to packets, routing packets across the world, and ensuring applications understand the data.

01.1 / Structure

Network Topologies

Topology defines the physical or logical layout of a network. It determines how devices connect and data flows.

Star Topology

All devices connect to a central Hub/Switch. Easy to troubleshoot, but if the Hub fails, the network goes down.

Mesh Topology

Devices interconnect redundantly. High reliability and fault tolerance, but expensive and complex cabling.

Bus Topology

Single cable (backbone) connects all devices. Easy to install, but a cable break stops the whole network.

Ring Topology

Devices connect in a circle. Data travels in one direction. Token passing controls access.

Tree Topology

Hierarchical structure with a root node. Scalable and manageable, often used in WANs.

Hybrid Topology

Integration of two or more different topologies (e.g., Star-Ring). Flexible but complex to design.

01.2 / Scope

Network Types

Networks are classified by their geographical scope, from a few meters (PAN) to the entire globe (WAN).

PAN

Person

Personal Area Network. Smallest range (approx. 10m). Connects personal devices.

Bluetooth, Zigbee

LAN

Local

Local Area Network. Connects devices in a single location like a home, office, or building. High speed.

Ethernet (802.3)

WLAN

Wireless

Wireless LAN. Uses radio waves to connect devices without cables. Flexible but subject to interference.

Wi-Fi (802.11)

CAN

Campus

Campus Area Network. Interconnects multiple LANs within a specific area like a university or military base.

Fiber Backbones

MAN

Metro

Metropolitan Area Network. Spans an entire city or large campus. Connects multiple LANs.

Cable TV, Metro Ethernet

WAN

Wide

Wide Area Network. Spans countries or continents. The Internet is the largest WAN.

Satellites, Fiber Optic

SAN

Storage

Storage Area Network. High-speed network providing block-level access to storage. Appears as local drives.

Fibre Channel

VPN

Virtual

Virtual Private Network. Extends a private network across a public one (Internet). Encrypted tunnel.

IPsec, OpenVPN
01 / Abstraction

The OSI Model (7 Layers)

The Open Systems Interconnection (OSI) model standardizes communication functions into 7 distinct layers.

Why Layering?

  • Interoperability: Different hardware and software can communicate if they follow the same standard protocols.
  • Abstraction: Complex details are hidden. A browser (L7) doesn't need to know about fiber optics (L1).
  • Troubleshooting: Helps isolate problems (e.g., "Is it a physical cable issue or a wrong IP address?").
L1 Physical
L2 Data Link
L3 Network
L4 Transport
L5 Session
L6 Presentation
L7 Application
Selected Layer

Select a Layer

Interact with the stack on the left to explore each layer's specific responsibilities in the network model.

Data Unit -
Examples -
01.3 / Data Flow

Encapsulation

As data moves down the stack, each layer adds a "Header" (and sometimes a Footer). This process is called Encapsulation.

User Data
Application
→
TCP H.
Data
Segment
→
IP Header
TCP
Data
Packet
→
MAC
..
..
FCS
Frame
02 / Transport

TCP/IP & Packet Switching

The Internet runs on TCP/IP. Data is broken into packets, routed independently, and reassembled at the destination.

The TCP 3-Way Handshake

Before data transfers, TCP guarantees a reliable connection:

1. SYN (Hello?)
2. SYN-ACK (Hello! I hear you.)
3. ACK (Great, let's connect.)
Client
Server
R1
R2
R3
02.1 / Addressing & Switching

Network Layer: IP & Switching

The Network Layer is responsible for logical addressing (IP) and routing packets from source to destination appropriately.

Packet Switching

Datagram Approach

Connectionless. Each packet is treated independently. Packets may take different paths and arrive out of order.

Used by: The Internet (IP)
Virtual Circuit

Connection-oriented. A pre-defined path is established before data transfer. All packets follow the same path.

Used by: ATM, Frame Relay

IP Addressing (IPv4 vs IPv6)

IPv4 Packet Header

Version
IHL
ToS
Total Length
Identification
Fragment Offset
TTL
Protocol
Header Checksum
Source IP Address (32 bits)
Destination IP Address (32 bits)
IPv4
  • Size: 32-bit (approx 4.3 billion addresses)
  • Format: Dotted Decimal (192.168.1.1)
  • Header: Variable length (20-60 bytes)
  • Config: Manual or DHCP
IPv6
  • Size: 128-bit (Undecillions of addresses)
  • Format: Hexadecimal (2001:0db8::1)
  • Header: Fixed length (40 bytes), Simpler processing
  • Config: Auto-configuration (SLAAC) built-in
CIDR Notation

Classless Inter-Domain Routing.

192.168.1.0/24
  • /24 = 255.255.255.0 (Subnet Mask)
  • 254 Usable Hosts
Private Ranges (RFC 1918)

Not routable on the internet.

  • 10.0.0.0/8 (Enterprise)
  • 172.16.0.0/12 (AWS/Cloud)
  • 192.168.0.0/16 (Home)
02.2 / Routing

Routing Protocols & Algorithms

How routers decide the best path for a packet. Algorithms build the map, protocols share the map.

Core Algorithms

Interactive Dijkstra (Shortest Path)
A
B
C
D
4 2 1 5 8
Find shortest path from A to D.
Result: ?
Distance Vector (DVR)

Bellman-Ford Algorithm. Routers define path by "Distance" (Metric) and "Vector" (Direction/Next Hop).

Issue: Count-to-Infinity problem.
Link State (LSR)

Dijkstra's Algorithm. Every router knows the complete graph (topology) of the network.

Heavy computation, fast convergence.
Path Vector (PVR)

Similar to DVR but stores the entire path history to prevent loops. Used between Autonomous Systems.

Unicast Routing Protocols

Protocol Type Metric Use Case
RIP (v1/v2) Distance Vector Hop Count (Max 15) Small Networks, LANs
OSPF Link State Cost (Bandwidth) Large Enterprise (Intra-AS)
BGP Path Vector Policy/Attributes Internet Core (Inter-AS)

Multicast Routing: MOSPF

Multicast Extensions to OSPF. Uses the Link State database to calculate a "Source-Based Tree" for efficient one-to-many delivery.

Pruning Grafting IGMP
02.3 / Protocols

Key Protocols

Interactive DNS Resolver

Trace path will appear here...

HTTP / HTTPS

80 443

HyperText Transfer Protocol. Application layer protocol for transmitting hypermedia documents (HTML).

GET POST PUT
Status Codes
200 OK
301 Moved
404 Not Found

DHCP

Dynamic Host Configuration Protocol. Automatically assigns IP addresses to devices on a network.

Telnet

Port 23

Telecommunications Network. Older protocol for remote login. Unlike SSH, it is insecure (plaintext).

SSH

Port 22

Secure Shell. Cryptographic protocol for operating network services securely over an unsecured network. Used for remote login.

$ ssh user@host

FTP

Port 21

File Transfer Protocol. Standard protocol used for the transfer of computer files between a client and server.

SMTP

Port 25

Simple Mail Transfer Protocol. The standard for sending emails across the Internet.

IMAP

Port 143

Internet Message Access Protocol. Used by email clients to retrieve messages from a mail server.

RDP

Port 3389

Remote Desktop Protocol. Microsoft protocol that provides a graphical interface to connect to another computer.

Cheat Sheet

Common Port Directory
Port Protocol Description
20, 21 FTP File Transfer Protocol (Data/Control)
22 SSH Secure Shell (Remote Management)
23 Telnet Insecure Remote Login (Plaintext)
25 SMTP Email Transmission (Outgoing)
53 DNS Domain Name System (Lookups)
67, 68 DHCP Automatic IP Assignment
80 HTTP Unsecured Web Traffic
110 POP3 Post Office Protocol (Email)
143 IMAP Modern Email Retrieval
443 HTTPS Secure Web (Encrypted)
3389 RDP Remote Desktop Protocol
02.4 / Web Protocols & Semantics

HTTP Semantics & Status Codes

The foundational protocol of the World Wide Web: request methods, idempotency, and the complete taxonomy of RFC 9110 status responses.

The Hypertext Transfer Protocol (HTTP) is an application-layer, stateless request-response protocol running over TCP (port 80 for HTTP, port 443 for TLS-encrypted HTTPS). A client (e.g. browser or API consumer) sends an HTTP Request consisting of a method (verb), a target URI, headers, and an optional payload body. The web server processes the request and responds with an HTTP Status Code—a standardized 3-digit integer summarizing the exact outcome of the transaction.

Protocol Anatomy & Idempotency Matrix

1. Wire Protocol Format

// Client Request
GET /api/v1/users/42 HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGci...
Accept: application/json
// Server Response
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
ETag: W/"68bba-18972"
Cache-Control: max-age=3600, public
{"id": 42, "name": "Grace Hopper"}

2. Safety vs. Idempotency

Understanding method semantics is critical for resilient API and network design, caching proxies, and automatic retry policies:

Safe Methods

Operations that are strictly read-only and never alter server resource state (e.g. GET, HEAD, OPTIONS). Browsers and CDNs can prefetch and cache them safely.

Idempotent Methods ($f(f(x)) = f(x)$)

Executing the exact same request multiple times leaves the server in the identical end-state as executing it once (e.g. PUT, DELETE, GET). When a network timeout occurs, HTTP clients can safely replay idempotent requests without duplicate side-effects.

HTTP Verb Safe? Idempotent? Request Body Primary Semantics
GET Yes Yes No Retrieve representation of target resource
POST No No Yes Submit data to be processed; create subordinate resource
PUT No Yes Yes Replace entire target resource with payload body
PATCH No No Yes Apply partial modifications/deltas to an existing resource
DELETE No Yes Optional Delete the specified resource from server storage
HEAD Yes Yes No Identical to GET, but response contains headers only (no body)
OPTIONS Yes Yes No Query communication options and CORS preflight allowances
1xx
Informational

Request received; protocol handshake in progress.

2xx
Success

Action received, understood, and accepted by server.

3xx
Redirection

Further action required by client to complete request.

4xx
Client Error

Request contains invalid syntax, missing auth, or bad params.

5xx
Server Error

Server failed to fulfill valid request due to internal error or gateway fault.

Interactive Catalog / Complete HTTP Status Code Explorer
200 OK
2xx Success
RFC Definition

The request succeeded. Standard response for successful HTTP requests (e.g. GET returning data, or POST returning a result).

Real-World Trigger Scenario
User visits https://example.com/api/items and server successfully returns JSON payload.
Relevant Headers

Content-Type, Content-Length, ETag, Cache-Control

Pro Tip: 200 should always carry a response body. If no response payload is needed, prefer 204 No Content.
401 vs. 403 (Auth Dilemma)

401 Unauthorized: Missing or invalid credentials (actually means Unauthenticated). Client must authenticate. Server sends WWW-Authenticate header.

403 Forbidden: The server authenticated you and knows who you are, but you do not have permission (e.g. a normal user requesting /admin).

301/302 vs. 307/308 (Redirection)

Historically, browsers rewritten POST requests to GET when receiving 301 (Permanent) or 302 (Found).

307 (Temporary) and 308 (Permanent) guarantee the HTTP method is strictly preserved: a POST will re-POST to the new URL without changing to GET.

502 vs. 504 (Gateway Failures)

502 Bad Gateway: Reverse proxy (Nginx, Cloudflare) received an invalid response, crash, or TCP reset from the upstream web service.

504 Gateway Timeout: Reverse proxy waited for upstream response, but the upstream application timed out before sending any bytes.

02.5 / Wireless

Wireless & Mobile

Wi-Fi Standards

From 802.11b to Wi-Fi 7 (802.11be). Trade-off between Range (2.4GHz) and Speed (5GHz/6GHz).

IEEE 802.11
2.4 GHz
Long Range
Slower
5 GHz
Med Range
Fast
6 GHz
Short Range
Ultra Fast
03.1 / Safety

Encryption & Security

Symmetric vs Asymmetric Encryption

Symmetric

Same key for encryption and decryption. Fast, but key exchange is risky.

AES, DES
Asymmetric (Public Key)

Public key encrypts, Private key decrypts. Foundation of SSL/TLS.

SSL/TLS Handshake
  1. Client sends "Hello" & ciphers.
  2. Server sends Public Key Certificate.
  3. Client verifies cert & sends Session Key.
  4. Switch to fast Symmetric encryption.
RSA, ECC

Interactive Encryption Box

// Output will appear here
03.2 / Access Control & Token Architecture

Authentication, Authorization & JWT

Safeguarding networked systems: verifying who the client is (AuthN), controlling what they can do (AuthZ), and transmitting cryptographically signed claims via JSON Web Tokens.

Every secure network service must answer two foundational questions on every HTTP request. Failing to strictly separate these concepts causes some of the most catastrophic security vulnerabilities in web architecture:

The Core Division / AuthN vs. AuthZ

Authentication (AuthN)

Identity
"Who are you?"

Verifies that a user, agent, or client machine is genuinely who they claim to be by validating credentials.

• Mechanisms: Passwords, Passkeys (WebAuthn/FIDO2), TOTP/MFA, Biometrics, mTLS, OIDC ID Tokens
• Failure Response: 401 Unauthorized
• Response Header: WWW-Authenticate: Bearer ...
Analogy: Your passport at airport immigration. It verifies your identity, but does not yet grant you entry to a plane.

Authorization (AuthZ)

Privilege
"What can you do?"

Evaluates permissions, roles, and policies to determine if an already-authenticated entity has permission to access a specific resource.

• Mechanisms: RBAC (Roles), ABAC (Attributes), Access Control Lists (ACL), OAuth Scopes
• Failure Response: 403 Forbidden
• Response Header: None required (plain rejection)
Analogy: Your boarding pass at the gate. Even with a verified passport, you are only authorized to sit in Seat 14B, not in First Class or the Cockpit.

Interactive Simulator: The Two-Gate Network Check

NETWORK GATEWAY INSPECTION Ready
// Select a persona and route above, then click "Dispatch Request".
RFC 7519 / JSON Web Tokens (JWT)

The Architecture of a Stateless Token

A JSON Web Token (JWT) is an open, compact, URL-safe standard representing claims between two parties. Unlike legacy session cookies that require a central database lookup for every incoming HTTP request, JWTs are stateless: any microservice possessing the verification key can authenticate and authorize the token in memory with zero database latency.

The 3 Parts of a JWT (Base64URL Encoded)
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c3JfOTQxMCIsIm5hbWUiOiJBZGEgTG92ZWxhY2UiLCJyb2xlIjoidXNlciIsImlhdCI6MTcxODAwMDAwMCwiZXhwIjoxNzE4MDAzNjAwfQ.GZcM2Z8qF9Xz_v8oG0L0dNxR1c_L9kQwY2A8fK4nP-A
1. Header (Metadata)

Defines token type and cryptographic algorithm used to sign the payload.

{
  "alg": "HS256",
  "typ": "JWT"
}
2. Payload (Claims)

Statements about the entity (subject, name, role) and expiration timestamp.

{
  "sub": "usr_9410",
  "name": "Ada Lovelace",
  "role": "user",
  "exp": 1718003600
}
3. Signature (Integrity)

Prevents tampering. Calculated over base64(Header) + "." + base64(Payload) with server secret.

HMACSHA256(
  base64Url(header) + "." +
  base64Url(payload),
  server_secret_key
)
Live Cryptographic Tamper Test

Test how the server detects if an attacker alters the payload in transit.

✅
Cryptographic Signature Valid
Token integrity is verified. Server accepts Ada Lovelace as role "user".
Architecture Trade-Offs / Sessions vs. Tokens
Architectural Attribute Stateful Sessions (Cookies) Stateless JWTs
State Location Server memory or central database (Redis) Client-side; self-contained within the token
Microservice Scaling Bottleneck: every service must query central session store Seamless: verified locally via public key
Instant Revocation / Logout Trivial: delete row in Redis / DB Complex: valid until exp timestamp unless blocklist kept
Overhead per Request Tiny: ~32 bytes Session ID Larger: ~500 to 1,500+ bytes in Authorization header
Critical Security Best Practices
1. Base64 is NOT Encryption

JWT payloads are readable by anyone who intercepts the network traffic. Never store sensitive passwords, credit card numbers, or proprietary PII inside a standard JWT payload.

2. Reject "alg: none" Exploits

Always enforce server-side algorithm whitelisting (e.g. HS256 or RS256). Flawed libraries historically accepted unverified tokens when attackers set "alg": "none".

3. Storage: Avoid localStorage

Tokens in localStorage are vulnerable to XSS theft. Best practice: store tokens in HttpOnly, Secure, SameSite=Strict cookies paired with short-lived (15 min) access tokens.

Glossary

Key Definitions

Topology

The physical or logical layout of a network (e.g., Star, Mesh).

OSI Model

The Open Systems Interconnection model standardizing communication into 7 layers.

Encapsulation

The process of adding headers/footers to data as it moves down the protocol stack.

TCP/IP

Transmission Control Protocol/Internet Protocol. The foundational communication stack of the internet.

Packet

A formatted unit of data carried by a packet-switched network.

IP Address

A unique numerical label assigned to each device connected to a computer network.

DNS

Domain Name System. Translates domain names (google.com) to IP addresses.

HTTP/HTTPS

HyperText Transfer Protocol. Application layer protocol for transmitting web documents.

HTTP Status Codes

Standardized 3-digit response codes (1xx–5xx) returned by servers indicating request outcomes (RFC 9110).

Idempotency

The property of certain HTTP methods (GET, PUT, DELETE) where making multiple identical requests has the same effect as making a single request.

Encryption

The process of encoding information so only authorized parties can access it.

SSL/TLS

Secure Sockets Layer/Transport Layer Security. Protocols for establishing authenticated and encrypted links.

Authentication (AuthN)

The process of verifying the identity of a client or user ("Who are you?"). Failure triggers 401 Unauthorized.

Authorization (AuthZ)

The process of verifying permissions and roles of an authenticated user ("What can you do?"). Failure triggers 403 Forbidden.

JWT (JSON Web Token)

A compact, URL-safe RFC 7519 standard containing a Header, Payload, and Signature for transmitting stateless claims.

Bearer Token

A security token giving access rights to whoever "bears" or presents it, transmitted via the HTTP Authorization: Bearer <token> header.

04 / Verification

Knowledge Check

Verify your understanding of Computer Network fundamentals. Pass the exam to earn your certificate.