Computer Networks - Master Notes
A complete, structured, and comprehensive reference guide covering fundamental to advanced Computer Networking concepts across all 12 weeks / modules.
Module 1: Computer Networks Fundamentals & Layered Models
1. What is a Computer Network?
A Computer Network is an interconnected collection of autonomous devices (nodes) that communicate with each other over transmission media using a set of rules called protocols.
- Primary Objectives: Resource sharing (hardware, software, data), reliable communication, load balancing, cost efficiency, scalability.
- Core Components of Data Communication:
- Sender: Device that originates data.
- Receiver: Destination device.
- Message: The data/information being transmitted.
- Medium: Physical path (wired cable or wireless radio waves).
- Protocol: Agreed set of rules governing communication.
2. Network Classifications by Geographic Scale
| Network Type | Full Name | Geographic Scope | Typical Bandwidth | Example / Use Case |
|---|---|---|---|---|
| PAN | Personal Area Network | ~10 meters | High (Wireless) | Bluetooth devices, Smartwatch to Phone |
| LAN | Local Area Network | Building / Room / Campus (~1 km) | Very High (1–10 Gbps) | Home WiFi, College Lab, Office Network |
| CAN | Campus Area Network | Multiple adjacent buildings | High | University Campus, Corporate Park |
| MAN | Metropolitan Area Network | City / Metropolitan Area (~50 km) | Medium-High | Cable TV Network, City-wide Fibre |
| WAN | Wide Area Network | Country / Global | Variable | The Internet, Enterprise Cross-Country WAN |
3. Network Topologies
Network topology defines the physical or logical layout of nodes and interconnections.
Detailed Comparison Matrix
| Topology | Key Characteristics | Advantages | Disadvantages | Failure Impact |
|---|---|---|---|---|
| Bus | Single backbone cable with terminators at both ends. | Inexpensive, easy to install for small networks. | Heavy collisions, difficult troubleshooting. | Main cable failure downs whole network. |
| Star | Central node (Switch/Hub) connects to all endpoints. | Easy to manage, isolated node failure, high scale. | Central switch is single point of failure. | Central node crash downs whole network. |
| Ring | Token passing along unidirectional circular loop. | No collisions, deterministic access time. | Unidirectional data delay, reconfiguration hard. | Single cable break breaks the ring loop. |
| Mesh | Fully connected ( links) or partially connected. | Dedicated links, maximum fault tolerance, secure. | Extremely expensive, complex cabling ( ports/node). | Individual link failure has zero network impact. |
| Hybrid | Combination of two or more topologies (e.g. Star-Bus). | Scalable, flexible according to layout requirements. | Complex design, costly maintenance. | Isolated to affected sub-segment. |
4. Layered Network Models: OSI vs. TCP/IP
OSI 7-Layer Reference Model vs. TCP/IP Model
(HTTP, DNS, SMTP, FTP, SSH)"] T3["Transport Layer
(TCP, UDP)"] T2["Internet Layer
(IP, ICMP, ARP, NAT)"] T1["Network Access Layer
(Ethernet, Wi-Fi, MAC)"] T4 --> T3 --> T2 --> T1 end L7 -.-> T4 L6 -.-> T4 L5 -.-> T4 L4 -.-> T3 L3 -.-> T2 L2 -.-> T1 L1 -.-> T1
Detailed OSI Layer Breakdown
| Layer # | Layer Name | Key Responsibilities & Functions | Protocol Data Unit (PDU) | Core Hardware & Protocols |
|---|---|---|---|---|
| 7 | Application | End-user network interfaces, high-level APIs. | Data | HTTP, HTTPS, DNS, FTP, SMTP, SSH |
| 6 | Presentation | Data formatting, MIME types, encryption/decryption, compression. | Data | SSL/TLS, JPEG, ASCII, MPEG |
| 5 | Session | Session setup, maintenance, checkpointing, teardown. | Data | NetBIOS, RPC, Sockets |
| 4 | Transport | End-to-end process delivery, segmentation, flow/congestion control. | Segment (TCP) / Datagram (UDP) | TCP, UDP, SCTP |
| 3 | Network | Logical addressing (IP), path routing, packet forwarding. | Packet | IP (v4/v6), ICMP, OSPF, BGP, Routers |
| 2 | Data Link | Physical addressing (MAC), framing, error detection, media access. | Frame | Ethernet, WiFi (802.11), Switches, Bridges |
| 1 | Physical | Bit transmission over physical medium, signal encoding, pinouts. | Bits | Cables, Fiber, Repeaters, Hubs, Modems |
[!TIP]
OSI Layer Mnemonic (Top-to-Bottom):
"Please Do Not Throw Sausage Pizza Away"
- Physical (1) Data Link (2) Network (3) Transport (4) Session (5) Presentation (6) Application (7)
[!NOTE]
Conceptual Memory Tricks:
- Port = Process: Port numbers uniquely identify the destination software process on a host Transport Layer.
- IP = Identity: IP addresses logically identify host interfaces on a global network Network Layer.
- MAC = Media: MAC addresses physically identify network interface cards on a local link Data Link Layer.
5. Encapsulation & Decapsulation
Data encapsulation occurs as user data travels down the sender stack, adding headers (and trailers) at each layer. Decapsulation occurs as data travels up the receiver stack.
6. Network Devices Masterclass
+-----------------------------------------------------------------------------------+
| OSI Layer | Device | Addressing Used | Primary Function |
+-----------+------------------+-----------------+----------------------------------+
| Layer 7 | Gateway | Application | Protocol conversion across stacks|
| Layer 3 | Router | IP Address | Inter-network routing & forwarding|
| Layer 2 | Switch / Bridge | MAC Address | Intra-network frame switching |
| Layer 1 | Hub / Repeater | None (Bits) | Signal amplification / Broadcast |
+-----------------------------------------------------------------------------------+Detailed Device Breakdown
Hub (Layer 1 - Physical):
- Mechanism: Repeats incoming electrical/optical signals out to ALL other connected ports (pure broadcast).
- Intelligence: Zero. Contains no MAC table or packet filtering logic.
- Domains: 1 Single Collision Domain across all ports, 1 Single Broadcast Domain.
- Drawbacks: High collision rate, severe bandwidth sharing, security vulnerability (packet sniffing).
Repeater (Layer 1 - Physical):
- Mechanism: Regenerates and amplifies attenuated signals to extend long cable runs.
- Operation: Works strictly on physical bits; does not inspect frames or packets.
Switch (Layer 2 - Data Link):
- Mechanism: Learns host MAC addresses by inspecting source fields of incoming frames and populates a CAM (Content Addressable Memory) Table.
- Operation: Performs Unicast forwarding based on destination MAC. If MAC is unknown or broadcast (
FF:FF:FF:FF:FF:FF), it floods out all ports except incoming. - Switching Modes:
- Store-and-Forward: Receives complete frame, checks CRC for errors, then forwards (Highest reliability).
- Cut-Through: Reads destination MAC (first 6 bytes) and starts forwarding immediately (Lowest latency).
- Domains: Provides Collision Domains (1 per port), but 1 Single Broadcast Domain (unless divided by VLANs).
Bridge (Layer 2 - Data Link):
- Mechanism: Software/Hardware device with few ports (typically 2) used to divide a large collision domain into smaller segments based on MAC addresses.
- Relation: A Switch is effectively a high-density, hardware-accelerated (ASIC) multi-port bridge.
Router (Layer 3 - Network):
- Mechanism: Connects distinct IP subnetworks. Inspects Destination IP address of incoming packets and queries its Routing Table to choose the best next-hop path.
- Functions: Routing, Packet Forwarding, Network Address Translation (NAT), Default Gateway processing.
- Domains: Separates both Collision Domains AND Broadcast Domains (Does not forward layer 2 broadcasts).
Gateway (All Layers):
- Mechanism: Converts data between completely incompatible network architectures and application protocols (e.g. Email-to-SMS Gateway, SNA-to-TCP/IP Gateway).
Modem (Layer 1 - Physical):
- Mechanism: Modulator-Demodulator. Converts digital bits from computer to analog signals (frequency/amplitude/phase modulation) for transmission over telephone/cable lines, and vice versa.
Wireless Access Point (AP - Layer 2):
- Mechanism: Acts as a wireless-to-wired bridge connecting Wi-Fi stations (802.11) to Ethernet LAN switches (802.3).
NIC (Network Interface Card):
- Scope: Operates across both Layer 1 (transceiver, physical connector) and Layer 2 (burned-in 48-bit MAC address, frame formatting, hardware CRC verification).
Module 2: Application Layer Protocols & Web Services
1. HTTP & HTTPS
Core Properties
- HTTP (Hypertext Transfer Protocol): Stateless client-server protocol operating over TCP port 80.
- HTTPS (HTTP Secure): Encrypted HTTP operating over SSL/TLS on TCP port 443.
HTTP Methods & Idempotency
| Method | Description | Safe? | Idempotent? |
|---|---|---|---|
| GET | Retrieve data/resource from server. | Yes | Yes |
| POST | Submit new data to server (creates resource). | No | No |
| PUT | Replace/create target resource state completely. | No | Yes |
| DELETE | Remove specified resource. | No | Yes |
| HEAD | Same as GET, but returns response headers only (no body). | Yes | Yes |
| OPTIONS | Describe communication options for target resource. | Yes | Yes |
| PATCH | Apply partial modifications to a resource. | No | No |
HTTP Status Codes
| Category | Range | Meaning | Famous Examples |
|---|---|---|---|
| 1xx | Informational | Request received, continuing process. | 100 Continue, 101 Switching Protocols |
| 2xx | Success | Action successfully received & accepted. | 200 OK, 201 Created, 204 No Content |
| 3xx | Redirection | Further action needed to complete request. | 301 Moved Permanently, 302 Found, 304 Not Modified |
| 4xx | Client Error | Bad syntax or request cannot be fulfilled. | 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found |
| 5xx | Server Error | Server failed to fulfill valid request. | 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout |
Evolution of HTTP Protocols
HTTP/1.1 (Persistent TCP) HTTP/2 (Multiplexed TCP) HTTP/3 (QUIC over UDP)
[TCP Conn] [TCP Conn] [UDP Datagrams]
Stream 1: [Req1] -> [Resp1] Stream 1: [Frame 1A][Frame 1B] Stream 1: [Packet 1]
Stream 2: [Req2] -> [Resp2] Stream 2: [Frame 2A][Frame 2B] Stream 2: [Packet 2]
(Suffers Head-of-Line Blocking) (Single TCP HOL Blocking remains) (Zero HOL Blocking)| Feature | HTTP/1.1 | HTTP/2 | HTTP/3 |
|---|---|---|---|
| Transport Layer | TCP (Port 80/443) | TCP (Port 443) | UDP / QUIC (Port 443) |
| Format | Plaintext ASCII | Binary Framing | Binary Framing |
| Multiplexing | No (Pipelining limited) | Yes (Multiple streams per TCP) | Yes (Independent streams) |
| HOL Blocking | Application & Transport level | Transport level (TCP drop stops all streams) | Eliminated (UDP packet drop affects 1 stream only) |
| Connection Setup | 1 RTT (TCP) + 1-2 RTT (TLS) | 1 RTT (TCP) + 1 RTT (TLS 1.3) | 0-RTT or 1-RTT (Combined Handshake) |
2. Domain Name System (DNS)
Overview
DNS resolves human-readable domain names (e.g. example.com) to logical IP addresses (93.184.216.34).
- Ports Used:
- UDP Port 53: Used for standard DNS queries/responses (size 512 bytes).
- TCP Port 53: Used for Zone Transfers between DNS servers and responses exceeding 512 bytes.
DNS Resolution Hierarchy
[ . Root DNS Servers ]
|
+---------------+---------------+
| |
[.com TLD Server] [.org TLD Server]
| |
[example.com Auth Server] [wikipedia.org Auth Server]Recursive vs. Iterative Queries
Recursive Query Flow: Iterative Query Flow:
Client ----> Local DNS ----> Root DNS Client ----> Local DNS ----> Root DNS
(Delegates whole job) Local DNS <---- (Returns TLD IP)
Local DNS ----> TLD DNS
Local DNS <---- (Returns Auth IP)
Local DNS ----> Auth DNSPrimary DNS Resource Records (RR)
| Record Type | Purpose | Example Value |
|---|---|---|
| A | Maps IPv4 address to hostname. | example.com. IN A 93.184.216.34 |
| AAAA | Maps IPv6 address to hostname. | example.com. IN AAAA 2606:2800:220:1:248:1893:25c8:1946 |
| CNAME | Canonical Name (Alias mapping to another domain). | www.example.com. IN CNAME example.com. |
| MX | Mail Exchange server responsible for domain. | example.com. IN MX 10 mail.example.com. |
| NS | Authoritative Name Server for domain. | example.com. IN NS ns1.example.com. |
| PTR | Pointer record (Reverse lookup: IP to Name). | 34.216.184.93.in-addr.arpa. IN PTR example.com. |
| TXT | Arbitrary text (Used for SPF, DKIM, verification). | v=spf1 include:_spf.google.com ~all |
3. Email Protocols (SMTP, POP3, IMAP)
[ Sender Client ] ---> (SMTP: Port 25/587) ---> [ Sender Mail Server ]
|
(SMTP: Port 25)
v
[ Receiver Client ] <--- (POP3/IMAP) <--- [ Receiver Mail Server ]| Feature | SMTP | POP3 | IMAP |
|---|---|---|---|
| Role | Pushing / Sending Email | Pulling / Downloading Email | Syncing / Managing Email |
| Default Port | Port 25 (Plain), Port 587 (TLS) | Port 110 (Plain), Port 995 (SSL) | Port 143 (Plain), Port 993 (SSL) |
| Server Storage | N/A (Relays message) | Downloads & deletes by default | Keeps emails on server sync |
| Multi-Device Support | N/A | Poor (Messages downloaded to 1 device) | Excellent (State synced across all) |
4. File Transfer Protocol (FTP)
FTP operates using two separate TCP connections:
Client Server
Control Connection (Port 21): Commands & Replies
==========================================================>
Data Connection (Port 20 / Ephemeral): File Transfer
<==========================================================- Control Connection (Port 21): Stays open throughout session. Handles commands, authentication, state.
- Data Connection (Port 20 in Active Mode): Opened temporarily per file transfer.
- Active Mode: Client sends
PORTcommand; Server connects from Port 20 back to Client data port. (Fails behind client NAT/Firewall). - Passive Mode (PASV): Client sends
PASVcommand; Server opens an ephemeral listener port and Client initiates data connection.
- Active Mode: Client sends
5. Socket Programming API & I/O Multiplexing
System Call Flow for TCP Socket Programming
Server Side Client Side
socket() socket()
| |
bind() (Assign IP + Port) |
| |
listen() (Mark ready) |
| |
accept() <--- [ 3-Way Handshake SYN ] ------- connect()
| |
(Blocks until client connects) |
| <======= Read / Write Data Exchange ======> |
close() close()Comparison of I/O Multiplexing System Calls
| System Call | Scaling Complexity | Max File Descriptors | Data Structure Passed | Key Advantage / Drawback |
|---|---|---|---|---|
select() |
scanning | 1024 (FD_SETSIZE) |
Bitmasks (fd_set) |
POSIX portable; Slow scanning, low limit. |
poll() |
scanning | Unlimited by OS | Array of pollfd structs |
No hard limit; Still requires linear scan. |
epoll() |
event-driven | Unlimited by OS | Kernel Red-Black Tree + Ready List | High performance for 10k+ concurrent connections. |
Module 3: Transport Layer & Flow/Congestion Control
1. Transport Layer Overview
- Primary Function: Provides logical, process-to-process communication across end systems.
- Multiplexing: Combining data streams from multiple application sockets into transport packets with Source Port numbers.
- Demultiplexing: Delivering incoming segments to correct application process using Destination Port numbers.
Classification of Port Numbers
[ 0 -------------- 1023 | 1024 ------------------- 49151 | 49152 ------------------- 65535 ]
Well-Known Ports Registered Ports Dynamic / Ephemeral Ports
(HTTP: 80, SSH: 22) (MySQL: 3306, Redis: 6379) (Assigned dynamically by OS)2. TCP vs. UDP Deep Comparison Matrix
| Feature | TCP (Transmission Control Protocol) | UDP (User Datagram Protocol) |
|---|---|---|
| Connection Type | Connection-Oriented (3-Way Handshake) | Connectionless (No setup) |
| Reliability | Guaranteed delivery (ACKs, Retransmissions) | Best-Effort (No ACKs, loss possible) |
| Data Stream | Byte-Stream (No record boundaries) | Datagram-Based (Preserves message boundaries) |
| Header Size | 20 Bytes (Base) up to 60 Bytes with options | Fixed 8 Bytes |
| Flow Control | Yes (Sliding Window / Receiver Window rwnd) |
No |
| Congestion Control | Yes (Slow Start, Congestion Avoidance, AIMD) | No |
| Ordering | Guaranteed ordered delivery via Sequence Numbers | Unordered |
| Speed / Overhead | Higher latency, larger overhead | Low latency, minimum overhead |
| Use Cases | Web (HTTP/HTTPS), File Transfer (FTP), Mail, SSH | Video Streaming, DNS, VoIP, Online Gaming |
3. TCP Header Structure & Flags
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Source Port | Destination Port |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Sequence Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Acknowledgment Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Data | Reserved |U|A|P|R|S|F| Window Size |
| Offset | |R|C|S|S|Y|I| |
| (4b) | (6b) |G|K|H|T|N|N| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Checksum | Urgent Pointer |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options (0 to 40 Bytes) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+TCP Flags Summary
- SYN (Synchronize): Initiates connection; synchronizes initial sequence numbers (ISN).
- ACK (Acknowledgment): Indicates
Acknowledgment Numberfield is valid. - FIN (Finish): Sender has no more data to send; initiates connection teardown.
- RST (Reset): Aborts connection immediately due to error or closed port.
- PSH (Push): Requests receiver to push buffered data immediately to application.
- URG (Urgent): Indicates
Urgent Pointerfield is valid.
4. TCP Lifecycle: Connection & Teardown
3-Way Handshake (Establishment): 4-Way Teardown (Termination):
Client Server Client Server
| | | |
| --- SYN (Seq=x) -----------> | | --- FIN (Seq=u) -----------> |
| | | |
| <--- SYN-ACK (Seq=y, ------- | | <--- ACK (Ack=u+1) --------- |
| Ack=x+1) | | |
| | | <--- FIN (Seq=v) ----------- |
| --- ACK (Ack=y+1) ---------> | | |
| | | --- ACK (Ack=v+1) ---------> |
[ESTABLISHED] [ESTABLISHED] [TIME_WAIT] [CLOSED]
| (2 * MSL Timer)
[CLOSED][!IMPORTANT]
Why isTIME_WAITState Needed?
- Ensures the final ACK from client reaches the server. If lost, server retransmits FIN.
- Allows old, stray segments from the closed connection to expire in the network so they don't corrupt a future connection using the same socket tuple.
5. Flow Control & Sliding Window Protocols
Core Definitions
- Transmission Delay (): (where = packet length in bits, = bandwidth in bps).
- Propagation Delay (): (where = distance, = propagation velocity).
- Round Trip Time (): (assuming symmetric channel).
- Parameter : .
Comparison of Sliding Window Protocols
Stop-and-Wait: Go-Back-N (GBN): Selective Repeat (SR):
Window = 1 Sender Window = 2^m - 1 Sender Window = 2^(m-1)
S: [1] -> S: [1][2][3][4] -> S: [1][2][3][4] ->
R: <- ACK1 R: <- ACK1, ACK2 R: <- ACK1, NACK3
S: [2] -> (Cumulative ACKs; retransmits (Individual ACKs; retransmits
all from lost packet) ONLY lost packet)| Parameter | Stop-and-Wait | Go-Back-N (GBN) | Selective Repeat (SR) |
|---|---|---|---|
| Sender Window () | |||
| Receiver Window () | |||
| Efficiency () | |||
| ACK Type | Individual | Cumulative | Individual / Selective |
| Retransmission on Loss | Single packet | All unacknowledged packets in window | Only the missing lost packet |
| Out-of-Order Buffering | No | No (Discarded) | Yes (Buffered at receiver) |
| Sequence Numbers ( bits) | Minimum 1 bit (0 or 1) |
6. Bandwidth-Delay Product (BDP) & Congestion Control
Bandwidth-Delay Product (BDP)
BDP represents the maximum number of bits that can be "in flight" in the network pipe at any single moment.
Congestion Control Mechanisms
Congestion Window (cwnd) Growth Phases:
cwnd
^
8 | /---- Congestion Avoidance (+1 MSS per RTT)
4 | /--------------/ <-- ssthresh reached
2 | /-----/ <-- Slow Start (Doubles per RTT)
1 | /---------/
+--------------------------------------------------------> Time (RTT)- Slow Start: Starts with . Doubles every RTT (). Continues until .
- Congestion Avoidance: When , increases linearly by per RTT ().
- Congestion Event Handling:
- Timeout (Severe Congestion):
Restarts in Slow Start. - 3 Duplicate ACKs (Mild Congestion / Fast Retransmit & Fast Recovery):
Enters Congestion Avoidance directly (Additive Increase Multiplicative Decrease - AIMD).
- Timeout (Severe Congestion):
Module 4: Network Layer, IP Addressing & QoS
1. Network Layer Responsibilities
- Logical Addressing: Assigning globally unique IP addresses to host interfaces.
- Routing: Computing optical/electrical paths across autonomous networks.
- Forwarding: Moving packets locally from input router interface to output router interface.
2. IPv4 Addressing & Subnetting
Classful Addressing Architecture
Class A: | 0 | Network (7 bits) | Host (24 bits) | 1.0.0.0 to 126.255.255.255
Class B: | 1 0 | Network (14 bits) | Host (16 bits) | 128.0.0.0 to 191.255.255.255
Class C: | 1 1 0 | Network (21 bits) | Host (8 bits) | 192.0.0.0 to 223.255.255.255
Class D: | 1 1 1 0 | Multicast Group (28 bits) | 224.0.0.0 to 239.255.255.255
Class E: | 1 1 1 1 | Experimental / Reserved | 240.0.0.0 to 255.255.255.255Special IPv4 Addresses
| Address / Range | Description | Usage |
|---|---|---|
0.0.0.0 / 0 |
Unknown host / Default route | Unspecified source IP during DHCP request. |
127.0.0.0 / 8 |
Loopback address range (127.0.0.1) |
IPC testing on local host. |
255.255.255.255 |
Limited Broadcast Address | Broadcasts to all hosts on local subnet (not routed). |
10.0.0.0 / 8 |
Private IPv4 Range (Class A) | Internal network addressing (RFC 1918). |
172.16.0.0 / 12 |
Private IPv4 Range (Class B) | Internal network addressing (RFC 1918). |
192.168.0.0 / 16 |
Private IPv4 Range (Class C) | Home router internal addressing (RFC 1918). |
169.254.0.0 / 16 |
Automatic Private IP Addressing (APIPA) | Auto-assigned when DHCP server is unreachable. |
CIDR & Subnetting Mathematics
For a subnet specified as /N:
- Host Bits (): .
- Total IP Addresses: .
- Usable Host Addresses: (Subtract Network Address where host bits = 0, and Broadcast Address where host bits = 1).
- Block Size (Magic Number): .
CIDR Subnet Mask Reference Table
| CIDR Prefix | Subnet Mask | Total IPs | Usable IPs | Host Bits () |
|---|---|---|---|---|
| /24 | 255.255.255.0 |
256 | 254 | 8 |
| /25 | 255.255.255.128 |
128 | 126 | 7 |
| /26 | 255.255.255.192 |
64 | 62 | 6 |
| /27 | 255.255.255.224 |
32 | 30 | 5 |
| /28 | 255.255.255.240 |
16 | 14 | 4 |
| /29 | 255.255.255.248 |
8 | 6 | 3 |
| /30 | 255.255.255.252 |
4 | 2 | 2 |
| /31 | 255.255.255.254 |
2 | 2 (Point-to-point RFC 3021) | 1 |
| /32 | 255.255.255.255 |
1 | Single Host | 0 |
3. IPv4 Header Format
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Version| IHL |Type of Service| Total Length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Identification |Flags| Fragment Offset |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Time to Live | Protocol | Header Checksum |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Source IP Address |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Destination IP Address |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options (if IHL > 5) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- IHL (Internet Header Length - 4 bits): Length of header in 32-bit (4-byte) words. Minimum value is , maximum is .
- Total Length (16 bits): Entire packet size (Header + Data) in bytes (Max ).
- Flags (3 bits): Bit 0 (Reserved), Bit 1 (DF - Don't Fragment), Bit 2 (MF - More Fragments).
- Fragment Offset (13 bits): Position of fragment in original datagram, measured in 8-byte units.
- TTL (Time To Live - 8 bits): Hop counter decremented by each router. Prevents infinite routing loops. (If TTL = 0, packet dropped and ICMP Time Exceeded sent).
- Protocol (8 bits): Indicates payload protocol (
1=ICMP,6=TCP,17=UDP,89=OSPF).
4. IPv6 Header & Comparison with IPv4
IPv6 Base Header (Fixed 40 Bytes):
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Version| Traffic Class | Flow Label |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Payload Length | Next Header | Hop Limit |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ Source Address +
| (128 bits) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ Destination Address +
| (128 bits) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+| Feature | IPv4 | IPv6 |
|---|---|---|
| Address Length | 32 Bits (4 Bytes) | 128 Bits (16 Bytes) |
| Format | Dotted Decimal (192.168.1.1) |
Hexadecimal (2001:db8::1) |
| Header Size | Variable (20 to 60 Bytes) | Fixed 40 Bytes |
| Header Checksum | Yes (Recalculated every hop) | None (Removed for faster processing) |
| Router Fragmentation | Yes (Routers fragment packets) | No (Sender performs PMTU discovery) |
| Address Auto-Config | DHCP or Static | SLAAC (Stateless) or DHCPv6 |
5. Network Address Translation (NAT) & PAT
NAT translates private non-routable IP addresses to a public routable IP.
[ Private Host ] [ NAT Router ] [ Web Server ]
IP: 192.168.1.50:5000 -------------------> [ Public IP: 203.0.113.1 ] -------------> IP: 140.82.112.4:80
Translate 192.168.1.50:5000 -> 203.0.113.1:12001- Static NAT: 1-to-1 permanent mapping of private IP to public IP.
- Dynamic NAT: M-to-N dynamic mapping from a pool of public IPs.
- PAT / NAPT (Port Address Translation / Overload): Maps thousands of private IPs to a single public IP using unique source port numbers.
6. Quality of Service (QoS) & Traffic Management
Key QoS Parameters
- Bandwidth: Maximum data rate capacity (bps).
- Delay / Latency: Time taken for packet to travel from source to destination.
- Jitter: Variation/Flakiness in packet arrival delay.
- Packet Loss: Percentage of packets dropped due to buffer overflow or noise.
Traffic Shaping vs. Traffic Policing
Traffic Shaping (Smoothes traffic via Buffer): Traffic Policing (Drops excess traffic):
Rate Rate
^ ^
| /\ /\ | --Dropped--
| / \/ \ ---> [ Buffer ] ---> [ Constant Rate ] | /----------\ ---> [ Truncated Rate ]
+--------------------------------------------> +-------------------------------------------->- Traffic Shaping: Buffers excess bursty packets and meters them out at a smooth, constant rate (e.g. Leaky Bucket). Adds latency, avoids drops.
- Traffic Policing: Checks arrival rate; if traffic exceeds threshold, excess packets are dropped immediately or re-marked (e.g. Token Bucket).
Leaky Bucket vs. Token Bucket
| Algorithm | Mechanism | Handles Bursty Traffic? | Output Rate |
|---|---|---|---|
| Leaky Bucket | Packets enter bucket; leak out at fixed rate. | No (Drops overflow) | Strictly Constant |
| Token Bucket | Tokens accumulate at rate ; burst allowed if tokens exist. | Yes (Up to bucket capacity ) | Variable / Bursty allowed |
Module 5: Routing Algorithms, Router Architecture & SDN
1. Control Plane vs. Data Plane
+-----------------------------------------------------------------------+
| CONTROL PLANE (Software / CPU) |
| Routing Protocols (OSPF, BGP) -> Computes Routing Table / Topology |
+-----------------------------------------------------------------------+
| (Installs rules)
v
+-----------------------------------------------------------------------+
| DATA PLANE (Hardware / ASIC) |
| Packet Forwarding -> Longest Prefix Match lookup in FIB -> Switch |
+-----------------------------------------------------------------------+Longest Prefix Match (LPM)
When a router receives a packet, it compares the destination IP against all entries in its forwarding table and chooses the entry with the most specific (longest) subnet mask match.
2. Routing Algorithms & Protocols
Distance Vector (DV) vs. Link State (LS)
Distance Vector (Bellman-Ford): Link State (Dijkstra):
Exchanges full table with immediate neighbors. Floods link states to ALL nodes in network.
(Local knowledge, Global scope) (Global knowledge, Local computation)| Parameter | Distance Vector (DV) | Link State (LS) |
|---|---|---|
| Algorithm | Bellman-Ford Algorithm | Dijkstra's Algorithm |
| Information Shared | Routing Table metrics | Link State Advertisements (LSA) |
| Sharing Scope | Neighbors only | All nodes in entire area (Flooding) |
| Convergence Speed | Slow | Fast |
| Protocol Example | RIP (Routing Information Protocol) | OSPF (Open Shortest Path First) |
| Routing Metric | Hop Count (Max 15) | Cost () |
| Loop Problems | Count-to-Infinity problem | No count-to-infinity loops |
Count-to-Infinity Problem & Mitigations
In Distance Vector networks, link failures can cause two routers to iteratively update metrics to infinity.
- Mitigations:
- Split Horizon: Never advertise a route back out the same interface from which it was learned.
- Poison Reverse: Advertise a failed link back out the same interface with metric = (16 in RIP).
- Triggered Updates: Send immediate update when link status changes (don't wait for timer).
Dijkstra Algorithm Step-by-Step Method
- Set distance for all nodes except source where .
- Maintain set of visited nodes . Initially .
- For current node , update neighbors :
- Choose unvisited node with smallest , add to , and repeat until all nodes visited.
Border Gateway Protocol (BGP)
- Scope: Exterior Gateway Protocol (EGP) used for routing between Autonomous Systems (AS) on the Internet.
- Transport: Runs over TCP Port 179.
- Type: Path-Vector Protocol (Advertises complete sequence of AS numbers to prevent loops).
- BGP Message Types:
OPEN: Establishes BGP peer session.UPDATE: Advertises new routes or withdraws revoked routes.KEEPALIVE: Periodically confirms peer session is alive.NOTIFICATION: Reports errors and closes session.
3. Router Architecture & Switching Fabrics
Input Port Structure:
[ Physical Line ] -> [ L1 Framing ] -> [ Lookup & Forwarding ] -> [ Switch Fabric Queue ]
|
(Subject to Head-of-Line Blocking if first packet in line is blocked) ----+- Switching Fabric Types:
- Memory: CPU copies packet between input and output buffers (Slowest).
- Bus: Input ports transfer packets directly to output ports over a shared bus (Subject to bus contention).
- Crossbar Matrix: Grid of buses allowing multiple parallel transmissions.
- Head-of-Line (HOL) Blocking: Occurs when a queued packet at an input port cannot be forwarded because the output port it needs is busy, thereby blocking all subsequent packets behind it in the same queue.
4. Software Defined Networking (SDN)
SDN decouples the network control logic from the underlying forwarding hardware.
+------------------------------------------------------------------+
| APPLICATION LAYER (SDN Apps) |
+------------------------------------------------------------------+
^
| Northbound API (REST / gRPC)
v
+------------------------------------------------------------------+
| CONTROL LAYER (SDN Controller) |
| (Centralized Control: ONOS / OpenDaylight) |
+------------------------------------------------------------------+
^
| Southbound API (OpenFlow)
v
+------------------------------------------------------------------+
| INFRASTRUCTURE LAYER (Data Plane) |
| [ OpenFlow Switch ] [ OpenFlow Switch ] |
+------------------------------------------------------------------+Module 6: Data Link Layer, Error Control & Media Access
1. Data Link Layer Sublayer Architecture
The Data Link Layer is divided into two IEEE sublayers:
- Logical Link Control (LLC - IEEE 802.2): Interfaces with the network layer, handles multiplexing and optional flow/error control.
- Media Access Control (MAC - IEEE 802.3/802.11): Handles physical hardware addressing, framing, and medium access arbitration.
2. Framing Techniques
| Technique | Description | Vulnerability / Mechanism |
|---|---|---|
| Character Count | Header contains integer length of frame. | Single bit error in count desynchronizes all subsequent frames. |
| Byte Stuffing | Uses FLAG byte (0x7E) to mark boundaries. |
Escapes data bytes matching FLAG or ESC by prefixing with ESC (0x1B). |
| Bit Stuffing | Uses 01111110 (6 ones) flag. |
Sender inserts a 0 after five consecutive 1s in data. Receiver strips it. |
3. Error Detection & Correction
Cyclic Redundancy Check (CRC)
CRC uses modulo-2 binary division via a Generator Polynomial of degree .
- Append zeros to data polynomial .
- Divide by using XOR binary division.
- The -bit remainder is appended to the data as the CRC checksum.
Data: 101000, Generator: 1101 (r = 3 bits)
Append 000 -> Dividend: 101000000
101000000 | 1101
^ 1101
------
1110
^ 1101
------
0110
^ 0000
------
1100
^ 1101
------
0010
^ 0000
------
0100
^ 0000
------
100 <-- Remainder (CRC = 100) -> Transmitted Frame: 101000100Hamming Code & Hamming Distance
- Hamming Distance (): Minimum number of bit flips required to convert one valid codeword into another.
- Error Detection: To detect single-bit errors:
- Error Correction: To correct single-bit errors:
- Parity Bits Formula (): For data bits and parity bits:
4. Medium Access Control (MAC) Protocols
Medium Access Control (MAC)
|
+-------------------------------+-------------------------------+
| | |
Random Access Protocols Controlled Access Protocols Channelization Protocols
- Pure ALOHA (18.4%) - Reservation - FDMA (Frequency)
- Slotted ALOHA (36.8%) - Polling (Master-Slave) - TDMA (Time)
- CSMA/CD (Ethernet) - Token Ring (Token Passing) - CDMA (Code / Orthogonal)
- CSMA/CA (WiFi)Detailed MAC Protocol Comparison
| Protocol | Medium Access Logic | Collision Action | Maximum Efficiency |
|---|---|---|---|
| Pure ALOHA | Transmit immediately whenever frame is ready. | Abort on collision; wait random backoff. | 18.4% () |
| Slotted ALOHA | Transmit only at designated time slot boundaries. | Retransmit in future slot. | 36.8% () |
| CSMA/CD | Listen before transmit; Listen while transmitting. | Transmit Jam signal; Binary Exponential Backoff. | Very High () |
| CSMA/CA | Listen before transmit; Collision Avoidance via RTS/CTS. | Wait DIFS/SIFS + Random Backoff timer. | High |
CSMA/CD Minimum Frame Size Formula
To ensure sender detects collisions before it finishes transmitting a frame:
Module 7: Network Infrastructure Protocols & Wireless Networks
1. ARP, RARP & BOOTP
ARP Request (Broadcast): "Who has IP 192.168.1.1? Tell MAC AA:BB:CC..."
Host A -------------------------------------------------------------> ALL HOSTS
|
ARP Reply (Unicast): "IP 192.168.1.1 is at MAC 11:22:33:44:55:66" v
Host A <------------------------------------------------------------- Host B- ARP (Address Resolution Protocol): Resolves known IP address unknown MAC address. (Layer 2 payload).
- RARP (Reverse ARP): Resolves known MAC address IP address (Used by legacy diskless hosts).
- BOOTP: Predecessor to DHCP; assigns IP statically via BOOTP table.
2. DHCP (Dynamic Host Configuration Protocol)
DHCP dynamically assigns IP addresses, subnet masks, default gateways, and DNS servers.
Client (UDP Port 68) Server (UDP Port 67)
| |
| --- DHCP DISCOVER (Broadcast: 255.255.255.255) -----> |
| |
| <-- DHCP OFFER (Unicast/Broadcast: Offered IP) ------ |
| |
| --- DHCP REQUEST (Broadcast: Confirms selection) ----> |
| |
| <-- DHCP ACK (Unicast/Broadcast: Lease confirmed) --- |[!TIP]
DHCP Mnemonic: D-O-R-A
Discover Offer Request Ack
3. Virtual LANs (VLAN) & IEEE 802.1Q
- VLAN Concept: Logically partitions a physical switch into multiple isolated broadcast domains.
- IEEE 802.1Q Header Tagging: Inserts a 4-byte Tag into the Ethernet frame. Contains VLAN ID (12 bits = 4096 VLANs).
- Switch Port Types:
- Access Port: Belongs to a single untagged VLAN (connects endpoints).
- Trunk Port: Carries multi-VLAN traffic across switches using 802.1Q tags.
4. Wireless LAN (IEEE 802.11 Wi-Fi)
Architecture
- BSS (Basic Service Set): 1 Access Point (AP) + connected wireless stations.
- ESS (Extended Service Set): Multiple BSSs connected via a wired Distribution System (DS) allowing seamless roaming/handoff.
Hidden & Exposed Terminal Problems
Hidden Terminal Problem: Exposed Terminal Problem:
[ Node A ] ---> (Receives B) <--- [ Node C ] [ Node A ] <-- [ Node B ] [ Node C ] --> [ Node D ]
(A and C cannot hear each other; transmit (B hears A transmitting to someone else;
simultaneously to B causing collision) unnecessarily refrains from transmitting to C)- Solution: RTS/CTS Handshake (Request to Send / Clear to Send) reserves channel prior to data transmission.
Module 8: Physical Layer & Network Security
1. Physical Transmission & Theoretical Limits
Guided vs. Unguided Media
- Guided (Wired): Twisted Pair (UTP/STP Cat5e/Cat6), Coaxial Cable, Fiber Optic (Single-Mode: Laser long haul; Multi-Mode: LED short haul).
- Unguided (Wireless): Radio waves (Omnidirectional), Microwaves (Line-of-sight directional), Infrared.
Fundamental Data Rate Formulas
Nyquist Bit Rate (Noiseless Channel):
(where = Bandwidth in Hz, = Number of signal levels)Shannon Capacity Theorem (Noisy Channel):
(where = Channel Capacity in bps, )
2. Network Security Foundations
The CIA Triad
- Confidentiality: Data readable only by authorized recipients (Achieved via Encryption).
- Integrity: Data cannot be modified undetected during transit (Achieved via Hashes/Signatures).
- Availability: Services remain operational for authorized users (Achieved via Redundancy/DDoS mitigations).
Attack Classifications
- Passive Attacks: Eavesdropping, Traffic Analysis (No content alteration; violates Confidentiality).
- Active Attacks: Spoofing, Replay, Message Modification, Denial of Service (DoS/DDoS) (Violates Integrity/Availability).
3. Cryptography Masterclass
Symmetric Encryption: Asymmetric Encryption:
[ Plaintext ] -> [ Shared Key K ] -> [ Ciphertext ] [ Plaintext ] -> [ Public Key ] -> [ Ciphertext ]
[ Ciphertext ] -> [ Shared Key K ] -> [ Plaintext ] [ Ciphertext ] -> [ Private Key ] -> [ Plaintext ]| Parameter | Symmetric Cryptography | Asymmetric Cryptography |
|---|---|---|
| Keys Used | 1 Shared Secret Key | Key Pair (Public Key & Private Key) |
| Speed | Extremely Fast (Hardware accelerated) | Slow (Computationally heavy math) |
| Key Distribution | Hard (Requires secure key exchange) | Easy (Public key distributed freely) |
| Algorithms | AES (128/256 bit), DES, 3DES, ChaCha20 | RSA, ECC, Diffie-Hellman, ECDHE |
[!NOTE]
ECDHE (Elliptic Curve Diffie-Hellman Ephemeral):
Key exchange protocol that provides Perfect Forward Secrecy (PFS) by generating temporary, disposable session keys. If a server's long-term private key is leaked in the future, past recorded traffic cannot be decrypted.
4. Hashes & Digital Signatures
- Cryptographic Hash Functions (SHA-256, MD5): One-way deterministic functions that produce a fixed-size digest. (Collision resistant).
- Digital Signatures: Sender encrypts a hash of the document using their Private Key. Receiver decrypts using Sender's Public Key. Provides Integrity, Authentication, and Non-Repudiation.
5. TLS / SSL Handshake Architecture
Client Server
| --- ClientHello (TLS Version, Ciphers, Client Random) ----> |
| |
| <--- ServerHello (Selected Cipher, Server Random) --------- |
| <--- Server Certificate (Contains Server Public Key) ------ |
| <--- ServerKeyExchange / ServerHelloDone ------------------ |
| |
| --- ClientKeyExchange (Pre-Master Secret encrypted) ------> |
| --- [ChangeCipherSpec] & Finished ------------------------> |
| |
| <--- [ChangeCipherSpec] & Finished ------------------------ |
| |
| <======= Encrypted Application Data (AES-GCM) ============> |6. Firewalls & IPSec
Firewall Generations
- Packet-Filtering Firewall (L3/L4): Inspects IP headers and Port numbers against ACL rules.
- Stateful Inspection Firewall (L3-L5): Maintains a connection state table tracking active TCP streams.
- Application Gateway / Proxy Firewall (L7): Deep packet inspection of HTTP/DNS application payloads.
IPSec (IP Security) Framework
Operates at the Network Layer (Layer 3) to secure IP traffic.
- Protocols:
- AH (Authentication Header): Provides Data Integrity and Authentication; No Encryption.
- ESP (Encapsulating Security Payload): Provides Data Integrity, Authentication, AND Confidentiality (Encryption).
- Modes:
- Transport Mode: Encrypts payload only; leaves original IP header visible (Host-to-Host).
- Tunnel Mode: Encrypts entire original IP packet and prepends a new outer IP header (Site-to-Site VPN).