Computer Networks
Subject 1 of 10 ยท from the OSI model to network security, with the tables and formulas that actually matter.
1. Network Basics & the OSI Model
The OSI (Open Systems Interconnection) model is a conceptual framework that standardizes how network communication is designed. It splits communication into seven distinct layers. Each layer provides services to the layer above it and receives services from the layer below. These layers form the foundation for understanding how data moves through networks, from raw physical signals up to application-level messages.
The seven layers
| Layer | Name | Function |
|---|---|---|
| 7 | Application | User interface, apps โ the services users touch directly |
| 6 | Presentation | Data formatting, encryption, compression |
| 5 | Session | Connection setup, management, teardown between apps |
| 4 | Transport | Reliable end-to-end data delivery |
| 3 | Network | Routing and logical addressing |
| 2 | Data Link | Frame formatting, node-to-node delivery |
| 1 | Physical | Electrical / optical signals, raw bits |
Two groups of layers
- Upper layers (5โ7) handle user-oriented functions: what applications see.
- Lower layers (1โ4) handle network-oriented functions: moving bits across the wire.
Data flows down the stack when sending and up the stack when receiving. The key benefit of the whole scheme is interoperability: equipment from different manufacturers can talk to each other because everyone standardizes against the same layer boundaries.
2. Network Topologies
Wireless networks are classified by their infrastructure.
Infrastructure mode
- Basic Service Set (BSS): one central access point connected to the wired network. Each station talks directly to the base station in a single hop. Example: a traditional Wi-Fi access point that all your devices join.
- Extended Service Set (ESS): multiple access points sharing one SSID, stitched together over the wired network. Extends coverage seamlessly โ your phone roams between APs without noticing.
Ad hoc networks
Infrastructure-less communication: no central base station, no wired backbone. Every node can act as both client and router, talking directly device-to-device.
- Self-organizing and self-healing
- Needs a distributed routing process
- Example: Bluetooth devices coordinating during an emergency with no cell coverage
Infrastructure mode = centralized control. Ad hoc = peer to peer.
3. Physical Layer
The Physical Layer sits at the very bottom of the OSI model. It handles the actual transmission of raw bits over the physical medium: managing the physical connection between devices, controlling how bits are pushed through cables, and converting raw bits into signals.
Key specifications
| Spec | What it defines |
|---|---|
| Electrical | Voltage levels representing binary 1 and 0 |
| Mechanical | Physical connectors, pin configurations, cable specs |
| Timing | Signal duration, synchronization between sender and receiver |
| Bandwidth | Data transmission rate, maximum channel capacity |
Transmission media
- Copper cables โ twisted pair, coaxial
- Fiber optic โ light-based, single-mode and multi-mode
- Wireless โ radio waves, microwaves
Signal characteristics define how long each bit is transmitted (bit duration = 1 / bandwidth) and the signaling method used (NRZ, Manchester, and friends).
The Physical Layer doesn't understand data meaning. It only knows how to push bits from one point to another. All the intelligence lives at higher layers.
4. Data Link Layer
The Data Link Layer (Layer 2) manages reliable transmission between directly connected nodes. Its jobs: framing, error detection, flow control, and mediating access to a shared medium.
Framing
Framing converts packets from the Network Layer into frames by adding a header and a trailer. Each frame carries a header with control information (like MAC addresses), the data payload, and a trailer with error-detection codes.
Where does one frame end and another begin in a continuous bit stream?
Error detection
An error-detection code is computed for each frame. The common methods:
- Checksums โ simple addition-based verification
- CRC (Cyclic Redundancy Check) โ polynomial division, robust detection
- Parity bits โ single-bit error detection
The receiver extracts frames from the bit stream, verifies integrity with the code, and requests retransmission if errors are found.
Ethernet (IEEE 802.3)
Ethernet defines both physical and data-link behavior for LANs. It is connectionless (no setup before sending) and best-effort (no acknowledgments, flow control, or error recovery at this layer). Classic Ethernet used a shared bus with CSMA/CD for medium access.
| Field | Size (bytes) | Content |
|---|---|---|
| Preamble | 7 | 1010โฆ10 โ synchronizes the receiver clock |
| SFD | 1 | 10101011 โ Start Frame Delimiter, marks the real frame start |
| Destination MAC | 6 | Who the frame is for |
| Source MAC | 6 | Who sent it |
| Length | 2 | Size of the data field in bytes |
| Data | 46โ1500 | Actual payload (padded to 46 bytes minimum) |
| CRC | 4 | 32-bit error-detection code |
Frame size limits
- Minimum: 64 bytes โ 6 + 6 + 2 + 46 + 4. The minimum exists so collision detection works properly across the maximum cable length: a frame must still be on the wire when a collision's echo returns.
- Maximum: 1518 bytes โ 6 + 6 + 2 + 1500 + 4.
CSMA/CD performance
d = cable length, v = signal speed, L = frame length in bits, R = bandwidth in bps
Key insight: longer frames improve efficiency by shrinking the relative cost of collision overhead. When N stations compete, the probability that exactly one transmits successfully in a slot is P = Nยทpยท(1โp)Nโ1, and the average contention period before success is k ร 2ฯ where k = 1/p.
Switched, full-duplex Ethernet eliminated collisions entirely, so CSMA/CD is legacy. It still matters for exams and for understanding shared-medium behavior.
ARP โ Address Resolution Protocol
ARP maps IP addresses to MAC addresses when a device needs to talk on its local network. A device knows the destination IP but needs the MAC to build the frame.
- ARP request: broadcast containing sender IP/MAC and target IP (target MAC unknown).
- ARP reply: unicast straight back to the requester with the target's MAC.
- ARP cache: mappings are cached ~20โ30 minutes, so repeat traffic to the same host needs no new broadcast.
- Encapsulation: ARP rides directly in Ethernet frames with EtherType 0x0806 โ no IP header involved.
Four use cases: host-to-host on the same network, host-to-router (needs the router's MAC), router-to-router (next-hop MAC), router-to-host (final delivery).
RARP and its successors
RARP did the reverse: given only a MAC address, get an IP (for diskless workstations). It needed a dedicated RARP server per segment and its broadcasts couldn't cross routers โ a scaling dead end. BOOTP extended the idea, and DHCP eventually replaced RARP entirely.
5. Flow Control & ARQ Protocols
Flow control regulates how fast a sender transmits so it never overwhelms the receiver. The classic family is ARQ โ Automatic Repeat reQuest.
Stop-and-Wait ARQ
The sender transmits one frame, then waits for its acknowledgment before sending the next. Simple, but the channel sits idle most of the time.
On a satellite link with 270 ms propagation delay and 1 ms transmission time, ฮท โ 1/(1+540) โ 0.0018 โ under 0.2% utilization. Stop-and-wait collapses wherever bandwidth is high or distance is long.
Go-Back-N ARQ
A sliding-window protocol: the sender may have up to N frames unacknowledged. The receiver only accepts in-order frames (receiver window = 1) and sends cumulative ACKs.
- Maximum window for N-bit sequence numbers: 2^N โ 1
- On timeout, the sender retransmits everything from the oldest unacknowledged frame โ simple, but wasteful on noisy links.
Selective Repeat ARQ
The efficient sibling: the receiver buffers out-of-order frames and the sender retransmits only the lost or corrupted ones. Each frame gets its own ACK. Maximum window is 2^(Nโ1) for N-bit sequence numbers.
Sliding window, summarized
| Protocol | Sender window | Receiver window | On loss |
|---|---|---|---|
| Stop-and-Wait | 1 | 1 | Resend the one frame |
| Go-Back-N | N | 1 | Resend all from the lost frame onward |
| Selective Repeat | N | N | Resend only the lost frame |
6. MAC Sublayer & Wireless LANs
CSMA/CA โ why wireless can't use CSMA/CD
On a wire, a station can listen while transmitting and detect collisions. On radio it can't โ its own transmission drowns out everything else. Two extra problems appear:
- Hidden terminal: two stations can't hear each other but both reach the access point; they collide unknowingly.
- Exposed terminal: a station holds off transmitting because it hears a neighbor, even though its own transmission wouldn't have interfered.
So 802.11 uses CSMA/CA (collision avoidance): listen first, then reserve the channel with an RTS/CTS handshake before sending data. Timing gaps keep things orderly: SIFS (short, for immediate responses like ACK/CTS) and DIFS (longer, before contending for the channel).
| Mode | Connection |
|---|---|
| Infrastructure | Via base station (access point) |
| Ad hoc | Device to device, no AP |
802.11 standards
| Standard | Frequency band | Max data rate |
|---|---|---|
| 802.11 (1997) | 2.4 GHz | 2 Mbps |
| 802.11a | 5 GHz | 54 Mbps |
| 802.11b | 2.4 GHz | 11 Mbps |
| 802.11g | 2.4 GHz | 54 Mbps |
| 802.11n | 2.4 / 5 GHz | up to 600 Mbps |
Joining a network: scanning
- Passive scanning: listen for the AP's periodic beacon frames. Cheap, slow.
- Active scanning: broadcast probe requests, APs answer with probe responses, then association request/response. Faster discovery, more airtime.
802.11 frame structure
| Field | Size | Notes |
|---|---|---|
| Frame Control | 2 bytes | Type, subtype, flags (below) |
| Duration / ID | 2 bytes | Channel reservation time |
| Address 1โ3 | 6 bytes each | Receiver, transmitter, BSSID/filtering addr |
| Sequence Control | 2 bytes | Fragment/sequence numbers |
| Address 4 | 6 bytes | Only in wireless distribution (AP-to-AP) |
| Frame Body | 0โ2312 bytes | The payload |
| FCS | 4 bytes | Frame check sequence |
Frame Control subfields (16 bits)
| Field | Bits | Purpose |
|---|---|---|
| Protocol Version | 2 | Always 0 so far |
| Type | 2 | Management / Control / Data |
| Subtype | 4 | e.g. beacon, RTS, CTS, ACK |
| To DS / From DS | 1 + 1 | Direction relative to the distribution system |
| More Fragments | 1 | More fragments of this frame follow |
| Retry | 1 | This is a retransmission |
| Power Management | 1 | Station entering power-save |
| More Data | 1 | AP has buffered frames for this station |
| Protected (WEP) | 1 | Frame is encrypted |
| Order | 1 | Strict ordering requested |
Token Ring (IEEE 802.5)
A deterministic LAN: stations sit on a ring and take turns transmitting by passing a small token frame. No collisions, ever โ you can only send while holding the token. A station may hold it for at most the Token Holding Time (THT), and priority levels (0โ7) let urgent traffic jump the queue. A dedicated monitor station keeps ring timing healthy and regenerates lost tokens.
| Ring speed | Max ring length |
|---|---|
| 4 Mbps | 1000 m |
| 16 Mbps | 500 m |
Higher speeds need shorter rings to keep signal quality up. Token frame: SD (1 byte) + AC (1 byte) + ED (1 byte).
| Aspect | Token Ring | Ethernet (classic) |
|---|---|---|
| Medium access | Token passing โ deterministic | CSMA/CD โ probabilistic |
| Collisions | None by design | Detected and retried |
| Efficiency | Stays high under heavy load | Degrades as contention rises |
| Reliability | Higher โ bounded access delay | Lower โ unbounded backoff |
| Best at | Sustained heavy load | Light, bursty load |
7. Network Layer & IP Addressing
The Network Layer (Layer 3) handles logical addressing and routing: assigning IP addresses, picking the best path, forwarding packets through routers, and fragmenting/reassembling packets that exceed a link's MTU.
Delivery types
- Unicast โ one to one
- Multicast โ one to many (group)
- Broadcast โ one to all on the network
IPv4 address classes
| Class | Range | Leading bits | Use |
|---|---|---|---|
| A | 0 โ 127 | 0xxx xxxx | Huge networks (224 hosts each) |
| B | 128 โ 191 | 10xx xxxx | Medium networks (216 hosts) |
| C | 192 โ 223 | 110x xxxx | Small networks (254 hosts) |
| D | 224 โ 239 | 1110 xxxx | Multicast |
| E | 240 โ 255 | 1111 xxxx | Experimental / reserved |
Special addresses worth memorizing: 0.0.0.0 (this network), 127.0.0.1 (loopback), 255.255.255.255 (limited broadcast), and the private ranges 10/8, 172.16/12, 192.168/16.
Subnetting
Subnetting borrows host bits to carve one network into smaller ones. A subnet mask (e.g. 255.255.255.0, or /24) splits the address into network + host portions. Benefits: less broadcast traffic, better address use, simpler routing through aggregation.
IPv4 header
| Field | Size | Purpose |
|---|---|---|
| Version | 4 bits | 4 for IPv4 |
| IHL | 4 bits | Header length in 32-bit words |
| Type of Service | 8 bits | QoS / priority hints |
| Total Length | 16 bits | Whole datagram in bytes |
| Identification | 16 bits | Groups fragments of one datagram |
| Flags | 3 bits | Don't-fragment / more-fragments |
| Fragment Offset | 13 bits | Position of this fragment |
| TTL | 8 bits | Hop countdown โ kills routing loops |
| Protocol | 8 bits | What rides inside: 6 = TCP, 17 = UDP |
| Header Checksum | 16 bits | Header integrity only |
| Source / Dest Address | 32 bits each | Endpoints |
| Options + Padding | variable | Rarely used extras |
IPv6 basics
128-bit addresses, written as eight hex groups (2001:db8::1), give ~3.4ร1038 addresses. The header is fixed at 40 bytes and simpler than IPv4's: no checksum (left to lower layers), no fragmentation fields (only the source fragments).
| Field | Size |
|---|---|
| Version | 4 bits |
| Traffic Class | 8 bits |
| Flow Label | 20 bits |
| Payload Length | 16 bits |
| Next Header | 8 bits |
| Hop Limit | 8 bits |
| Source Address | 128 bits |
| Destination Address | 128 bits |
IPv6 Next Header values
| Value | Header |
|---|---|
| 0 | Hop-by-Hop Options |
| 6 | TCP |
| 17 | UDP |
| 41 | Encapsulated IPv6 |
| 43 | Routing Header |
| 44 | Fragment Header |
| 50 | ESP (encrypted payload) |
| 51 | AH (authentication header) |
| 58 | ICMPv6 |
| 59 | No Next Header |
| 60 | Destination Options |
ICMP
The Internet Control Message Protocol is IP's error-reporting sidekick: destination-unreachable, time-exceeded (that's what traceroute exploits), echo request/reply (ping). It reports problems; it doesn't fix them.
8. Routing Algorithms
Distance Vector (RIP)
Each router keeps a vector of (destination, distance) and periodically shares it with neighbors. Bellman-Ford underneath. Simple, but slow to converge โ and infamous for the count-to-infinity problem when a link dies. Fixes: split horizon, poison reverse, holddown timers.
Link State (OSPF)
Each router learns the full topology, then runs Dijkstra locally. The five steps:
- Discover neighbors, learn their network addresses
- Measure the cost (delay) to each neighbor
- Bundle it into a link-state packet
- Flood the packet to all routers
- Compute the shortest path tree to every destination
Fast convergence, hierarchical areas to keep large networks manageable.
Path Vector (BGP)
The protocol of the internet backbone: inter-autonomous-system routing. Instead of raw distances, routers exchange full paths, which kills count-to-infinity and lets operators enforce policy ("don't route through AS X").
9. Transport Layer
The Transport Layer manages reliable data delivery between applications on different hosts: segmentation, port-based addressing, connection control, flow control, error control, and congestion control. It delivers end-to-end reliability regardless of what the network underneath does.
TCP โ Transmission Control Protocol
TCP is connection-oriented and reliable: a byte stream with acknowledgments and retransmissions. Connections are point-to-point, with a sliding window for flow control.
- Connection establishment: three-way handshake (SYN โ SYN-ACK โ ACK).
- Connection termination: four-way handshake with FIN segments.
- Sequence numbers: every byte is numbered; the initial sequence number is randomized per connection.
| Field | Size (bits) |
|---|---|
| Source Port | 16 |
| Destination Port | 16 |
| Sequence Number | 32 |
| Acknowledgment Number | 32 |
| Header Length | 4 |
| Reserved | 6 |
| Control Flags | 6 |
| Window Size | 16 |
| Checksum | 16 |
| Urgent Pointer | 16 |
| Options | variable |
Control flags: SYN, ACK, FIN, RST, PSH, URG.
Well-known TCP ports
| Protocol | Port | Purpose |
|---|---|---|
| HTTP | 80 | Web browsing |
| HTTPS | 443 | Secure web |
| FTP | 21 | File transfer (control) |
| SSH | 22 | Secure remote terminal |
| SMTP | 25 | Sending email |
| DNS | 53 | Domain name resolution |
TCP congestion control
Congestion control keeps the network from collapsing under load, balancing efficiency with fairness. The classic algorithm has four phases:
- Slow start: congestion window grows exponentially (doubling per RTT) to probe available capacity fast.
- Congestion avoidance: past the threshold, growth turns linear (additive increase) โ one segment per RTT.
- Fast retransmit: three duplicate ACKs trigger immediate resend, no waiting for the timeout.
- Fast recovery: halve the window instead of dropping back to slow start.
TCP also runs four timers: retransmission (resend unacked segments), persist (probe a zero-window receiver), keepalive (check idle connections), and time-wait (linger after close so late duplicates die).
UDP โ User Datagram Protocol
UDP is connectionless and unreliable โ no handshake, no ordering, no flow or congestion control. What it buys is speed and simplicity: message-oriented datagrams with an 8-byte header.
| UDP header (8 bytes) | |
|---|---|
| Source Port (16 bits) | Destination Port (16 bits) |
| Length (16 bits) | Checksum (16 bits, optional) |
| Feature | UDP | TCP |
|---|---|---|
| Connection | Connectionless | Connection-oriented |
| Reliability | Unreliable | Reliable |
| Speed | Faster | Slower |
| Use cases | Streaming, gaming, DNS | Web, email, file transfer |
Well-known UDP ports: DNS 53, DHCP 67/68, TFTP 69, SNMP 161, RIP 520.
10. Application Layer
The top of the stack: network services delivered directly to end-user applications โ file transfer, email, web access, directory services. These are the protocols users actually touch.
| OSI layer | Primary protocols |
|---|---|
| Application | HTTP, FTP, SMTP, DNS |
| Presentation | TLS, SSL, MIME |
| Session | NetBIOS, PPTP, RDP |
| Transport | TCP, UDP, SCTP |
| Network | IP, ICMP, ICMPv6 |
| Data Link | Ethernet, Wi-Fi (802.11) |
| Physical | Hubs, repeaters, cabling |
DNS โ Domain Name System
Translates human-readable names into IP addresses so nobody memorizes numbers. A hierarchical distributed database: root servers โ TLD servers โ authoritative servers. A lookup for example.com goes: local cache โ root โ .com TLD โ authoritative server โ IP back to you. Runs on UDP port 53 (TCP for zone transfers and large responses), with caching at every level.
BOOTP & DHCP
BOOTP let diskless workstations boot: broadcast a request with your MAC, get back an IP configuration. Static mappings, one server per network (relays forward across networks).
DHCP extends BOOTP with dynamic, leased addresses from a pool โ the reason your phone just works on any Wi-Fi. The four-step dance (DORA):
- Discover โ client broadcasts "any DHCP server out there?"
- Offer โ server(s) respond with a proposed address
- Request โ client picks one and asks for it
- ACK โ server confirms, lease timer starts
HTTP โ Hyper Text Transfer Protocol
The web's protocol: application-layer, client-server, running over TCP port 80. Stateless โ each request stands alone (cookies and sessions are layered on top, not part of HTTP itself).
HTTP methods
| Method | What it does |
|---|---|
| GET | Retrieve data from the server |
| POST | Submit data to the server |
| PUT | Replace / update a resource |
| DELETE | Remove a resource |
| HEAD | Headers only, no body |
| OPTIONS | Ask what methods a resource supports |
| TRACE | Echo the request back for debugging |
| CONNECT | Open a tunnel (how HTTPS proxies work) |
HTTP connection types
| Type | Behavior |
|---|---|
| Non-persistent | A new TCP connection per request |
| Persistent | One TCP connection reused for many requests |
| Pipelining | Send multiple requests without waiting for responses |
FTP โ File Transfer Protocol
Runs over TCP with two connections: port 21 carries commands and responses (control), port 20 carries the actual file data. Two modes for opening the data connection:
- Active: the server connects back to the client โ simple, but client firewalls hate it.
- Passive: the client opens both connections โ firewall-friendly, the modern default. Extended passive mode covers IPv6.
Relatives: TFTP (trivial FTP, port 69 โ no authentication, tiny, used for booting devices) and SFTP (FTP tunneled over SSH, port 22 โ not to be confused with FTPS, which is FTP over TLS).
SMTP, POP3, IMAP โ email
SMTP (port 25, submission on 587) only sends mail โ pushing messages between servers. MIME extends it to attachments and non-ASCII text. Reading mail is a different job:
| Feature | POP3 (port 110) | IMAP (port 143) |
|---|---|---|
| Storage | Local device | Server |
| Access | Download, then usually delete from server | Sync โ mail stays on server |
| Multi-device | Poor | Excellent |
| Server storage | Minimal | High |
This is why your phone, laptop, and webmail all show the same inbox: IMAP.
SSH โ Secure Shell
Encrypted remote login and command execution on port 22 โ the replacement for plaintext Telnet. Handles session management, strong authentication, and full encryption of everything in the session. Also the transport under SFTP and Git-over-SSH.
11. Network Security
Cryptography basics
- Plaintext โ the original readable message
- Ciphertext โ the encrypted, unreadable form
- Key โ the secret that parameterizes the transformation
The strength of cryptography depends on the key, not on keeping the algorithm secret.
Types of cryptography
| Type | How it works | Examples |
|---|---|---|
| Symmetric | One shared key encrypts and decrypts | DES, AES |
| Asymmetric | Public key encrypts, private key decrypts | RSA, Diffie-Hellman |
| Hash functions | One-way digest โ integrity, not secrecy | MD5, SHA-1, SHA-256 |
- DES: 56-bit key, 64-bit blocks. Broken by brute force โ do not use.
- AES: 128-bit blocks with 128, 192, or 256-bit keys. The current standard.
Common hash algorithms
| Algorithm | Digest size | Notes |
|---|---|---|
| MD2 | 128 bits | Oldest, obsolete |
| MD4 | 128 bits | Fast, but broken |
| MD5 | 128 bits | Enhanced MD4 โ collision-broken, avoid |
| SHA-1 | 160 bits | Five 32-bit words from 512-bit blocks โ deprecated |
| SHA-256 | 256 bits | Current safe default |
MACs and digital signatures
- MAC (Message Authentication Code): a keyed hash using a shared secret. Proves the message wasn't altered and came from someone holding the key.
- Digital signature: the sender signs the message digest with their private key; anyone verifies with the public key. Gives integrity, authentication, and non-repudiation โ the sender can't deny sending it.
For long messages, symmetric cryptography is far more efficient than asymmetric โ so real systems mix them: asymmetric to exchange a key, symmetric for the bulk data.
Eavesdropping
A passive attack: the attacker taps transmission lines and silently captures packets โ no modification, so it leaves no trace. On a shared Ethernet segment, sniffing tools can harvest passwords, emails, and file transfers sent in plaintext. Targets: serial lines, Ethernet traffic, wireless transmissions, and any unencrypted protocol (HTTP, Telnet, FTP). Defense: encrypt everything in transit (HTTPS, SSH, VPN) and physically secure the infrastructure.
Firewalls, DoS & DDoS
Firewalls filter traffic at network boundaries by rules โ what gets in, what stays out.
A Denial-of-Service attack targets availability, not data: flood the target with traffic, burn its CPU/memory/bandwidth, and legitimate requests starve. A Distributed DoS coordinates thousands of compromised machines (a botnet) at once โ far harder to block, since there's no single source to filter. A botnet of 1000 machines each sending 100 requests/second is 100,000 requests/second โ enough to flatten most web servers.
Common vectors: TCP SYN floods, UDP floods, HTTP request flooding, resource exhaustion (memory, disk). Defenses: rate limiting, traffic filtering, load balancing across servers, dedicated DDoS protection services.
Unlike attacks that steal data, DoS is purely about disrupting service availability.