OSI, TCP/IP, routing, congestion control, protocols and interview-focused networking fundamentals.
The Open Systems Interconnection (OSI) model is a conceptual framework with 7 layers that standardizes the functions of a communication system. Each layer serves a specific purpose and communicates with the layers above and below it. Mnemonic (bottom-up): Please Do Not Throw Sausage Pizza Away (Physical, Data Link, Network, Transport, Session, Presentation, Application).
| Layer | Name | PDU | Key Protocols | Key Devices | Function |
|---|---|---|---|---|---|
| 7 | Application | Data | HTTP, FTP, DNS, SMTP, DHCP | Gateway, Firewall | Provides network services to user applications; interface to the network |
| 6 | Presentation | Data | SSL/TLS, JPEG, ASCII, MPEG | Gateway | Data format translation, encryption, compression, encoding |
| 5 | Session | Data | NetBIOS, PPTP, RPC, SAP | Gateway | Establishes, manages, and terminates sessions between applications |
| 4 | Transport | Segment | TCP, UDP, SCTP | Firewall, Load Balancer | End-to-end connection, reliability, flow control, multiplexing |
| 3 | Network | Packet | IP, ICMP, ARP, OSPF, BGP | Router, Layer-3 Switch | Logical addressing (IP), routing, path determination |
| 2 | Data Link | Frame | Ethernet, PPP, HDLC, VLAN | Switch, Bridge, NIC | Framing, MAC addressing, error detection (FCS), LAN communication |
| 1 | Physical | Bits | RS-232, DSL, ISDN, USB | Hub, Repeater, Cable | Physical transmission of raw bit streams over a medium |
| Type | Direction | Description |
|---|---|---|
| Encapsulation | Top to Bottom | Each layer adds its own header (and trailer) to data from the layer above |
| Decapsulation | Bottom to Top | Each layer strips its header and passes remaining data up |
| Peer Communication | Same layer, different hosts | Each layer on sender communicates logically with the same layer on receiver via headers |
| Layer | Header Added | Trailer Added |
|---|---|---|
| Application (7) | Application data (payload) | -- |
| Presentation (6) | Encryption / encoding info | -- |
| Session (5) | Session ID, synchronization | -- |
| Transport (4) | TCP/UDP header (port, seq, ack) | -- |
| Network (3) | IP header (src/dst IP, TTL) | -- |
| Data Link (2) | Frame header (MAC, type) | FCS (CRC) |
| Physical (1) | Bits on wire | -- |
┌─────────────────────────────────────────────────────┐
│ APPLICATION DATA │ ← User data
├─────────────────────────────────────────────────────┤
│ TCP/UDP HEADER │ APPLICATION DATA │ ← Transport Layer (Segment)
├─────────────────┴───────────────────────────────────┤
│ IP HEADER │ TCP/UDP HEADER │ APPLICATION DATA │ ← Network Layer (Packet)
├─────────────┴──────────────────┴────────────────────┤
│ FRAME HDR │ IP HDR │ TCP/UDP HDR │ DATA │ FCS │ ← Data Link Layer (Frame)
├───────────┴────────┴─────────────┴──────┴───────────┤
│ 01010101010101010101010101 │ ← Physical Layer (Bits)| Feature | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented (3-way handshake) | Connectionless |
| Reliability | Reliable (ACK, retransmission, sequencing) | Unreliable (best-effort delivery) |
| Ordering | Guaranteed order of packets | No ordering guarantee |
| Flow Control | Sliding window protocol | None |
| Congestion Control | Slow start, congestion avoidance | None |
| Header Size | 20-60 bytes | 8 bytes (fixed) |
| Speed | Slower (overhead) | Faster (minimal overhead) |
| Transmission | Byte stream | Datagrams (messages) |
| Use Cases | Web browsing, email, file transfer | Streaming, gaming, DNS, VoIP, SNMP |
| Multiplexing | Port numbers (16-bit) | Port numbers (16-bit) |
| Error Detection | Checksum (mandatory) | Checksum (optional) |
| Broadcast/Multicast | Not supported | Supported |
Step 1: Client sends SYN (seq = x) to server. Client moves to SYN_SENT state. Step 2: Server sends SYN-ACK (seq = y, ack = x+1). Server moves to SYN_RCVD state. Step 3: Client sends ACK (seq = x+1, ack = y+1). Both move to ESTABLISHED state. This ensures both sides are ready and agree on initial sequence numbers (ISN).
Step 1: Client sends FIN (seq = u). Client moves to FIN_WAIT_1. Step 2: Server sends ACK (ack = u+1). Server moves to CLOSE_WAIT, client to FIN_WAIT_2. Step 3: Server sends FIN (seq = v). Server moves to LAST_ACK. Step 4: Client sends ACK (ack = v+1). Client moves to TIME_WAIT (waits 2*MSL), then CLOSED.
TCP 3-WAY HANDSHAKE TCP 4-WAY TERMINATION
───────────────────────── ─────────────────────────
Client Server Client Server
│ │ │ │
│──── SYN (seq=x) ────────>│ │──── FIN (seq=u) ────────>│
│ SYN_SENT │ │ FIN_WAIT_1 │
│<─── SYN+ACK ─────────────│ │<─── ACK (ack=u+1) ───────│
│ ESTABLISHED │ │ FIN_WAIT_2 CLOSE_WAIT│
│──── ACK (ack=y+1) ──────>│ │<─── FIN (seq=v) ─────────│
│ ESTABLISHED ESTABLISHED │ TIME_WAIT LAST_ACK │
│ │ │──── ACK (ack=v+1) ──────>│
│ │ │ TIME_WAIT (2*MSL) │
│ │ │ CLOSED │| Field | Size | Description |
|---|---|---|
| Source Port | 16 bits | Sending application port (0-65535) |
| Destination Port | 16 bits | Receiving application port |
| Sequence Number | 32 bits | Byte number of first byte in segment |
| Acknowledgment Number | 32 bits | Next expected byte from other side |
| Data Offset | 4 bits | TCP header length (in 32-bit words) |
| Flags (URG, ACK, PSH, RST, SYN, FIN) | 6 bits | Control flags for connection management |
| Window Size | 16 bits | Number of bytes receiver can accept (flow control) |
| Checksum | 16 bits | Error detection for header + data |
| Urgent Pointer | 16 bits | Offset to urgent data (when URG=1) |
| Mechanism | Description | Trigger |
|---|---|---|
| Slow Start | cwnd starts at 1 MSS, doubles each RTT (exponential growth) | Connection start or after timeout |
| Congestion Avoidance | cwnd increases by 1 MSS per RTT (linear growth, AIMD) | When cwnd reaches ssthresh |
| Fast Retransmit | Retransmit immediately after 3 duplicate ACKs (no RTO wait) | 3 duplicate ACKs received |
| Fast Recovery | cwnd = ssthresh + 3*MSS, avoids slow start after fast retransmit | After fast retransmit |
SLIDING WINDOW PROTOCOL (Flow Control)
─────────────────────────────────────────
Window = number of bytes sender can send without receiving an ACK
Sender Side: Receiver Side:
┌──────────────────────┐ ┌──────────────────────┐
│ [Sent & ACKed] [Sent │ [Window] │ Received & ACKed │
│ but not ACKed] │ [Usable] │ Window size = N │
└──────────────────────┘ └──────────────────────┘
• Window slides forward as ACKs are received
• Window shrinks if receiver advertises a smaller window
• If window = 0 → sender pauses (persist timer probes)
Example: Window size = 4
Send bytes 1,2,3,4 → wait for ACK → ACK for 1 received → slide → send 5 zero window probe mode, sending periodic probes until the window reopens.An IP address is a unique identifier assigned to every device on a network. IPv4 uses 32-bit addresses (4.3 billion total, written in dotted decimal like 192.168.1.1). IPv6 uses 128-bit addresses (3.4 x 10^38 total, written in hex like 2001:0db8:85a3::8a2e:0370:7334).
| Class | Range | Default Subnet Mask | Network Bits | Host Bits | Max Hosts | Use Case |
|---|---|---|---|---|---|---|
| A | 1.0.0.0 - 126.255.255.255 | 255.0.0.0 (/8) | 8 | 24 | 16,777,214 | Very large networks |
| B | 128.0.0.0 - 191.255.255.255 | 255.255.0.0 (/16) | 16 | 16 | 65,534 | Medium-large networks |
| C | 192.0.0.0 - 223.255.255.255 | 255.255.255.0 (/24) | 24 | 8 | 254 | Small networks (LANs) |
| D | 224.0.0.0 - 239.255.255.255 | N/A (multicast) | N/A | N/A | N/A | Multicast groups |
| E | 240.0.0.0 - 255.255.255.255 | N/A (reserved) | N/A | N/A | N/A | Experimental / Reserved |
| Class | Private Range | CIDR | Usable Hosts |
|---|---|---|---|
| A | 10.0.0.0 - 10.255.255.255 | 10.0.0.0/8 | 16,777,214 |
| B | 172.16.0.0 - 172.31.255.255 | 172.16.0.0/12 | 1,048,574 |
| C | 192.168.0.0 - 192.168.255.255 | 192.168.0.0/16 | 65,534 |
Private IPs are not routable on the public Internet. NAT (Network Address Translation) maps private IPs to a public IP for Internet access.
| Address | Name | Purpose |
|---|---|---|
| 0.0.0.0 | Unspecified | Default route, "any address" |
| 127.0.0.1 | Loopback | Points back to the local machine |
| 224.0.0.0 | Multicast base | Start of multicast address range |
| 255.255.255.255 | Broadcast | Limited broadcast to all hosts on local network |
| 169.254.0.0/16 | Link-Local (APIPA) | Auto-assigned when DHCP fails |
| ::1 | IPv6 Loopback | IPv6 equivalent of 127.0.0.1 |
CIDR replaces classful addressing with a prefix notation (/n) to specify the number of network bits. For example, 192.168.1.0/24 means the first 24 bits are the network portion, leaving 8 bits for hosts. Subnet mask = 255.255.255.0. Number of subnets = 2^borrowed bits. Number of hosts per subnet = 2^host bits - 2. CIDR allows variable-length subnet masks (VLSM), meaning different subnets can have different sizes.
NAT maps private IP addresses to a single (or few) public IP address(es) for Internet access. Static NAT: 1-to-1 mapping (private IP <-> public IP). Dynamic NAT: maps to a pool of public IPs. PAT (Port Address Translation / NAT Overload): maps multiple private IPs to a single public IP using different ports. NAT conserves IPv4 addresses and adds a layer of security by hiding internal IPs.
IPv6 ADDRESSING BASICS
───────────────────────────
Format: 8 groups of 4 hex digits separated by colons
Example: 2001:0db8:85a3:0000:0000:8a2e:0370:7334
Shorthand Rules:
• Leading zeros can be omitted: 2001:db8:85a3:0:0:8a2e:370:7334
• Consecutive zero groups (::) can be compressed (only once):
2001:db8:85a3::8a2e:370:7334
IPv6 Address Types:
• Unicast: Single interface (2001:db8::/32)
• Multicast: Group (ff00::/8)
• Anycast: Nearest of group (assigned from unicast space)
• Link-Local: fe80::/10 (auto-configured, non-routable)
• Loopback: ::1 (equivalent to 127.0.0.1)
• Unique Local: fc00::/7 (equivalent to RFC 1918 private IPs)
IPv4 to IPv6 Transition:
• Dual-stack: Run both IPv4 and IPv6 simultaneously
• Tunneling: Encapsulate IPv6 packets inside IPv4 (6to4, Teredo)
• NAT64/DNS64: Translate IPv6 to IPv4 on the flySubnetting divides a large network into smaller sub-networks (subnets) for better management, reduced broadcast domains, and improved security. VLSM (Variable Length Subnet Masking) allows subnets of different sizes.Supernetting (Route Aggregation / CIDR) combines multiple smaller networks into a larger one.
Step 1: Determine the number of subnets needed -> find the number of bits to borrow from host portion: 2^n >= required subnets.
Step 2: Calculate new subnet mask: original mask + borrowed bits.
Step 3: Calculate block size (magic number): 256 - interesting octet value.
Step 4: List subnets: start at 0, increment by block size.
Step 5: For each subnet: network = start, broadcast = end, first host = network + 1, last host = broadcast - 1.
Step 6: Usable hosts per subnet: 2^remaining_host_bits - 2 (subtract network and broadcast).
| Subnet | Network Address | Usable Range | Broadcast | Subnet Mask |
|---|---|---|---|---|
| 1 | 192.168.1.0 | 192.168.1.1 - 192.168.1.62 | 192.168.1.63 | 255.255.255.192 (/26) |
| 2 | 192.168.1.64 | 192.168.1.65 - 192.168.1.126 | 192.168.1.127 | 255.255.255.192 (/26) |
| 3 | 192.168.1.128 | 192.168.1.129 - 192.168.1.190 | 192.168.1.191 | 255.255.255.192 (/26) |
| 4 | 192.168.1.192 | 192.168.1.193 - 192.168.1.254 | 192.168.1.255 | 255.255.255.192 (/26) |
Worked-out: 4 subnets need 2 bits (2^2 = 4). Borrow 2 bits from host portion (8 bits -> 6 host bits). New mask = /26 (255.255.255.192). Block size = 256 - 192 = 64. Hosts per subnet = 2^6 - 2 = 62.
| Subnet | Network Address | Usable Range | Broadcast | Subnet Mask |
|---|---|---|---|---|
| 1 | 10.0.0.0 | 10.0.0.1 - 10.0.3.254 | 10.0.3.255 | 255.255.252.0 (/22) |
| 2 | 10.0.4.0 | 10.0.4.1 - 10.0.7.254 | 10.0.7.255 | 255.255.252.0 (/22) |
| 3 | 10.0.8.0 | 10.0.8.1 - 10.0.11.254 | 10.0.11.255 | 255.255.252.0 (/22) |
| 4 | 10.0.12.0 | 10.0.12.1 - 10.0.15.254 | 10.0.15.255 | 255.255.252.0 (/22) |
Worked-out: Need 500+ hosts: 2^n - 2 >= 500 ->n = 9 (2^9 = 512, 510 usable). Keep 9 host bits. From /16, network bits = 32 - 9 = 23. New mask = /23? Wait — let us recalculate. Actually: need 2^h - 2 >= 500 -> h = 9 bits for hosts. New prefix = 32 - 9 = /23. Block size in 3rd octet = 256 - 254 = 2. Hosts per subnet = 2^9 - 2 = 510. Subnets = 2^(23-16) = 128.
| Parameter | Value | Calculation |
|---|---|---|
| IP Address | 172.16.5.50/23 | Given |
| Subnet Mask | 255.255.254.0 | /23 = 8+8+7 bits |
| Block Size | 2 (in 3rd octet) | 256 - 254 = 2 |
| Network Address | 172.16.4.0 | 5.50: 5 is odd, floor to even multiple of 2: 4.0 |
| Broadcast Address | 172.16.5.255 | Next network is 172.16.6.0, so broadcast = 172.16.5.255 |
| First Host | 172.16.4.1 | Network + 1 |
| Last Host | 172.16.5.254 | Broadcast - 1 |
| Usable Hosts | 510 | 2^9 - 2 |
SUBNETTING QUICK REFERENCE (CIDR TABLE)
─────────────────────────────────────────
Prefix Subnet Mask Hosts Class C Subnets
/24 255.255.255.0 254 1
/25 255.255.255.128 126 2
/26 255.255.255.192 62 4
/27 255.255.255.224 30 8
/28 255.255.255.240 14 16
/29 255.255.255.248 6 32
/30 255.255.255.252 2 64 (point-to-point links)
/31 255.255.255.254 0* 128 (RFC 3021, no broadcast)
/32 255.255.255.255 1 256 (single host)
* /31 is used for point-to-point links (no network/broadcast needed)
POWERS OF 2 (memorize these!)
2^0=1 2^1=2 2^2=4 2^3=8 2^4=16
2^5=32 2^6=64 2^7=128 2^8=256 2^9=512
2^10=1024 2^11=2048 2^12=4096Supernetting combines multiple contiguous networks into a single larger network, reducing routing table size. Find the common prefix bits of all networks. Example: 192.168.0.0/24, 192.168.1.0/24,192.168.2.0/24, 192.168.3.0/24 -> supernet = 192.168.0.0/22. Method: Convert all network addresses to binary, find the common leading bits. 192.168.0.0 = 11000000.10101000.00000000.00000000 192.168.3.0 = 11000000.10101000.00000011.00000000 Common bits = first 22 bits -> /22.
VLSM allows different subnets to have different masks, wasting fewer IPs. Always start with the largest subnet first.Example: You have 192.168.1.0/24 and need: 1 subnet with 100 hosts, 2 subnets with 50 hosts, 4 subnets with 25 hosts.
- 100 hosts: need 2^7 - 2 = 126 -> /25 -> 192.168.1.0/25 (uses .0-.127)
- 50 hosts: need 2^6 - 2 = 62 -> /26 -> 192.168.1.128/26 (uses .128-.191), 192.168.1.192/26 (uses .192-.255)
Wait — we ran out of space! Start over with more careful planning using a VLSM table.
| Type | Description | Pros | Cons | Protocol Examples |
|---|---|---|---|---|
| Static | Manually configured routes by administrator | No overhead, secure, predictable | Does not scale, no failover | Manually entered |
| Dynamic | Routers automatically learn and exchange routes | Scales, auto-failover, adapts | Protocol overhead, complexity | RIP, OSPF, BGP |
| Feature | Description |
|---|---|
| Algorithm | Bellman-Ford equation |
| Knowledge | Only knows about neighbors |
| Metric | Hop count (RIP: max 15 hops) |
| Update | Periodic (every 30s for RIP), sends entire routing table |
| Convergence | Slow (count-to-infinity problem) |
| Loop Prevention | Split horizon, route poisoning, hold-down timers |
| Protocols | RIP (v1, v2), IGRP (deprecated) |
| Feature | Description |
|---|---|
| Algorithm | Dijkstra (Shortest Path First - SPF) |
| Knowledge | Complete topology map of the network |
| Metric | Cost (configurable: bandwidth, delay) |
| Update | Triggered (on change) + periodic LSA flooding |
| Convergence | Fast (seconds) |
| Loop Prevention | Full topology awareness eliminates loops |
| Protocols | OSPF, IS-IS |
BGP (Border Gateway Protocol) is the routing protocol of the Internet. It exchanges routing information between autonomous systems (AS). BGP is a path vector protocol — it tracks the path (sequence of AS numbers) to each destination rather than just distance. BGP does NOT use metrics like hop count or cost. Instead, it uses path attributes (AS_PATH, LOCAL_PREF, MED, etc.) and policies to select the best path.
iBGP: runs within the same AS; eBGP: runs between different ASes. BGP speakers are called BGP peers or BGP neighbors.
| Field | Description |
|---|---|
| Destination Network | The network address this route points to |
| Subnet Mask | Mask to identify the network portion of the destination |
| Next Hop / Gateway | IP address of the next router to forward the packet to |
| Interface | Local interface through which to send the packet |
| Metric / Administrative Distance | Cost of the route (lower is better); AD: trustworthiness (0-255) |
SAMPLE ROUTING TABLE
──────────────────────
Destination Gateway Genmask Flags Metric Iface
0.0.0.0 192.168.1.1 0.0.0.0 UG 100 eth0
192.168.1.0 0.0.0.0 255.255.255.0 U 0 eth0
10.0.0.0 192.168.1.2 255.0.0.0 UG 50 eth0
Legend:
U = Up (interface is up)
G = Gateway (route uses a gateway)
Administrative Distance (lower = more trusted):
Connected: 0 (directly attached network)
Static: 1 (manually configured)
OSPF: 110 (link state)
IS-IS: 115
RIP: 120 (distance vector)
eBGP: 20 (external BGP)
iBGP: 200 (internal BGP)
Unknown: 255 (never used)ROUTING PROTOCOLS COMPARISON
──────────────────────────────
Feature RIP OSPF BGP
──────────────────────────────────────────────────────────
Type Distance Vec Link State Path Vector
Algorithm Bellman-Ford Dijkstra (SPF) Path Selection
Scope AS AS Inter-AS (Internet)
Metric Hop count Cost (bandwidth) Path attributes
Max Hops 15 Unlimited Unlimited
Update Periodic 30s Triggered + LSA Incremental / triggered
Convergence Slow Fast Varies
VLSM Support RIP v2 yes Yes Yes
Hierarchy Flat Areas (Area 0 core) AS-level
Best For Small LANs Enterprise ISPs, large networksThe Data Link Layer (Layer 2) is responsible for framing (encapsulating packets into frames), MAC addressing, error detection, and LAN communication. It is divided into two sublayers: LLC (Logical Link Control) — provides flow control and multiplexing; and MAC (Media Access Control) — handles addressing and channel access.
| Technique | Description | Detects | Corrects |
|---|---|---|---|
| Parity Check (Even/Odd) | Add 1 parity bit to make total 1s even or odd | Odd number of bit errors | No |
| Two-Dimensional Parity | Parity bits for rows AND columns | Some burst errors | Single-bit correction |
| Checksum | Sum of all 16-bit words, 1s complement | Most errors | No |
| CRC (Cyclic Redundancy Check) | Polynomial division remainder | All single/double/burst errors up to frame length | No (but detects reliably) |
| Feature | Description |
|---|---|
| Size | 48 bits (6 bytes), written as hex pairs |
| Format | MM:MM:MM:SS:SS:SS (e.g., 00:1A:2B:3C:4D:5E) |
| OUI (First 3 bytes) | Organizationally Unique Identifier — vendor/manufacturer |
| NIC (Last 3 bytes) | Unique identifier assigned by manufacturer |
| Broadcast | FF:FF:FF:FF:FF:FF (sent to all devices on LAN) |
| Unicast | Specific device MAC address |
| Multicast | First bit of first byte = 1 (01:xx:xx:xx:xx:xx) |
| Feature | Hub | Switch (Layer 2) | Router (Layer 3) |
|---|---|---|---|
| OSI Layer | Layer 1 (Physical) | Layer 2 (Data Link) | Layer 3 (Network) |
| Function | Repeats signal to all ports | Forwards frames based on MAC table | Routes packets based on IP routing table |
| Addressing | None | MAC addresses | IP addresses |
| Broadcast Domain | Single (all ports) | Single (all ports in VLAN) | One per interface (isolated) |
| Collision Domain | One per port (shared) | One per port (dedicated) | One per interface (dedicated) |
| Intelligence | None (dumb device) | Learns MAC addresses (CAM table) | Full routing intelligence |
| Broadcast Handling | Floods to all ports | Floods to all ports | Does NOT forward broadcasts |
| Duplex Mode | Half-duplex only | Full-duplex | Full-duplex |
| Use Case | Rarely used (legacy) | LAN connectivity | WAN / inter-network routing |
Ethernet is the dominant LAN technology. It uses CSMA/CD (Carrier Sense Multiple Access with Collision Detection) in half-duplex mode: listen before sending, detect collisions, use exponential backoff. In modern full-duplex switches, CSMA/CD is effectively disabled. Frame size: min 64 bytes (including header), max 1518 bytes (standard). Ethernet II frame: Preamble (8B) | Dest MAC (6B) | Src MAC (6B) | EtherType (2B) | Data (46-1500B) | FCS (4B).
VLANs logically segment a physical network into multiple broadcast domains without additional hardware. Benefits: Security (isolate traffic), reduced broadcast domains, flexibility (devices in different physical locations can be in the same VLAN).
Access Port: carries traffic for a single VLAN (untagged). Trunk Port: carries traffic for multiple VLANs (uses 802.1Q tags — adds a 4-byte VLAN tag to the Ethernet frame).
802.1Q Tag: inserts 4 bytes after the source MAC: TPID (0x8100) | PCP | DEI | VLAN ID (12 bits). VLAN IDs: 1-4094 (default VLAN = 1). Native VLAN (untagged on trunk): usually VLAN 1.
ARP (Address Resolution Protocol)
──────────────────────────────────
Maps IP address to MAC address (Layer 3 -> Layer 2)
Process:
1. Host A wants to send to Host B (same network)
2. A checks its ARP cache for B's MAC
3. If not found, A broadcasts ARP Request:
"Who has 192.168.1.10? Tell 192.168.1.1"
4. B replies with ARP Reply (unicast):
"192.168.1.10 is at 00:11:22:33:44:55"
5. A caches the mapping in its ARP table
ARP Cache Entry Types:
• Dynamic: Learned via ARP, times out (typically 2-20 min)
• Static: Manually configured, permanent
ARP Commands:
arp -a # Display ARP table
arp -d # Delete an entry
arp -s # Add a static entryDNS translates human-readable domain names to IP addresses. It uses a hierarchical distributed database.
DNS Query Types:
- Recursive Query: Client asks DNS resolver; resolver does ALL the work and returns the final answer.
- Iterative Query: Client (or resolver) asks each server, which refers to the next server.
DNS Record Types:A (IPv4 address), AAAA (IPv6), CNAME (alias),MX (mail server), NS (name server), PTR (reverse lookup),SOA (start of authority), TXT (text records).
DNS Hierarchy: Root -> TLD (.com, .org) -> Authoritative Name Server -> Record. Port: 53 (UDP for queries, TCP for zone transfers).
HTTP (Hypertext Transfer Protocol) — stateless request-response protocol. Port 80.
HTTP Methods:GET (retrieve), POST (create/submit),PUT (replace), PATCH (partial update),DELETE (remove), HEAD (headers only),OPTIONS (allowed methods).
HTTP Status Codes:
- 1xx: Informational
- 2xx: Success (200 OK, 201 Created, 204 No Content)
- 3xx: Redirection (301 Permanent, 302 Temporary, 304 Not Modified)
- 4xx: Client Error (400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found)
- 5xx: Server Error (500 Internal, 502 Bad Gateway, 503 Unavailable)
HTTPS: HTTP over TLS/SSL. Port 443. Provides encryption, authentication, integrity.
HTTP/2: Multiplexing, header compression, server push, binary framing.
HTTP/3: Uses QUIC (UDP-based) instead of TCP for faster connections.
| Protocol | Port | Purpose | Description |
|---|---|---|---|
| SMTP | 25, 587, 465 | Send email | Push protocol: client sends emails to server; server-to-server delivery |
| POP3 | 110, 995 (SSL) | Receive email | Download and delete from server; simple, stores locally |
| IMAP | 143, 993 (SSL) | Access email | Access emails on server; syncs across devices; supports folders |
DHCP automatically assigns IP addresses and network configuration to devices. Uses DORA process:
Discover: Client broadcasts DHCP Discover (destination: 255.255.255.255).
Offer: Server responds with DHCP Offer (proposed IP + lease time).
Request: Client requests the offered IP (DHCP Request).
Ack: Server confirms the lease (DHCP Ack).
Ports: 67 (server), 68 (client). Lease time typically 8 days. DHCP uses UDP and operates at the application layer, but manages network-layer configuration.
FTP transfers files between client and server. Uses 2 connections:
- Control connection: Port 21 (TCP) — sends commands (USER, PASS, RETR, STOR, QUIT).
- Data connection: Port 20 (active mode) or random port (passive mode) — transfers file data.
Active Mode: Server initiates data connection to client (problematic with firewalls/NAT).
Passive Mode: Client initiates both connections (firewall-friendly).
SFTP (SSH FTP): FTP over SSH, port 22. Encrypted, secure.
TFTP (Trivial FTP): UDP port 69. No authentication, simpler but unreliable.
ICMP is used for diagnostics and error reporting at the network layer. It is NOT used for data transfer.
Key ICMP Messages:
- Echo Request/Reply (Type 8/0): Used by ping
- Destination Unreachable (Type 3): Host, port, or network unreachable
- Time Exceeded (Type 11): TTL expired (used by traceroute)
- Redirect (Type 5): Tells host of a better route
ping: Tests reachability and round-trip time.
traceroute: Maps the path to destination by incrementing TTL values. ICMP does NOT use port numbers. It sits between Layer 3 (Network) and Layer 4 (Transport).
WELL-KNOWN PORTS (0-1023)
───────────────────────────
Port Protocol Application
──── ────────── ──────────────────────────────────
20/21 FTP File Transfer Protocol (data/control)
22 SSH Secure Shell
23 Telnet Remote login (unencrypted)
25 SMTP Simple Mail Transfer Protocol
53 DNS Domain Name System
67/68 DHCP Dynamic Host Configuration (server/client)
69 TFTP Trivial File Transfer Protocol
80 HTTP Hypertext Transfer Protocol
110 POP3 Post Office Protocol v3
119 NNTP Network News Transfer Protocol
123 NTP Network Time Protocol
143 IMAP Internet Message Access Protocol
161 SNMP Simple Network Management Protocol
194 IRC Internet Relay Chat
443 HTTPS HTTP over TLS/SSL
465 SMTPS SMTP over SSL
587 SMTP SMTP submission port
993 IMAPS IMAP over SSL
995 POP3S POP3 over SSL
3306 MySQL MySQL databaseSSH=22, HTTP=80, HTTPS=443, DNS=53, SMTP=25, FTP=21, DHCP=67/68, POP3=110, IMAP=143. Also know that DNS primarily uses UDP (port 53) for queries but falls back to TCP for zone transfers and large responses.| Feature | Symmetric Encryption | Asymmetric Encryption |
|---|---|---|
| Keys | Single shared key (secret key) | Key pair: public key + private key |
| Speed | Fast (hardware-accelerated) | Slow (~1000x slower than symmetric) |
| Key Distribution | Problematic (must share key securely) | Easy (public key can be shared openly) |
| Use Cases | Bulk data encryption (AES, DES, 3DES) | Key exchange (RSA, Diffie-Hellman), digital signatures |
| Examples | AES-128/192/256, DES, 3DES, Blowfish | RSA, ECC, DSA, Diffie-Hellman |
| Key Length | 128-256 bits (AES) | 2048-4096 bits (RSA) |
| Math Basis | Substitution, permutation, XOR | Trapdoor one-way functions (factoring, discrete log) |
Step 1: ClientHello — Client sends supported TLS versions, cipher suites, and a random number.
Step 2: ServerHello — Server picks TLS version and cipher suite, sends its random number and digital certificate.
Step 3: Key Exchange— Client verifies server's certificate (CA chain), generates pre-master secret, encrypts it with server's public key, and sends it. Both sides derive the session key.
Step 4: Change Cipher Spec — Both sides switch to encrypted communication using the session key (symmetric).
Step 5: Finished— Both sides send encrypted "Finished" message to verify the handshake.
After this, all data is encrypted with symmetric encryption (AES) using the shared session key.
| Algorithm | Output Size | Status | Use |
|---|---|---|---|
| MD5 | 128 bits | BROKEN (collisions found) | Legacy, NOT for security |
| SHA-1 | 160 bits | BROKEN (theoretical collisions) | Legacy, being phased out |
| SHA-256 | 256 bits | Secure | Digital signatures, certificates, blockchain |
| SHA-384 | 384 bits | Secure | High-security applications |
| SHA-512 | 512 bits | Secure | Maximum security applications |
| bcrypt | Variable (cost factor) | Secure for passwords | Password hashing (slow by design) |
Digital signatures provide authentication, non-repudiation, and integrity.
Signing (sender): (1) Compute hash of the message using SHA-256. (2) Encrypt the hash with sender's private key using RSA. (3) Send message + encrypted hash (signature) to receiver.
Verification (receiver): (1) Decrypt the signature using sender's public key to get the hash. (2) Compute hash of the received message. (3) Compare both hashes — if they match, the message is authentic and untampered.
Key point: Anyone can verify the signature using the public key, but only the private key holder can create it.
Firewalls control network traffic based on security rules.
Packet Filtering Firewall: Filters based on source/destination IP, port, protocol. Fast but basic (Layer 3/4).
Stateful Firewall: Tracks connection state (TCP handshake). Understands if traffic is part of an established connection.
Application-Level Firewall (Proxy): Inspects Layer 7 (application data). Can filter by URL, content type.
Next-Gen Firewall (NGFW): Combines all above + intrusion prevention (IPS), deep packet inspection (DPI), application awareness.
WAF (Web Application Firewall): Protects web apps from OWASP Top 10 (SQL injection, XSS, CSRF).
VPNs create encrypted tunnels over public networks for secure communication.
IPsec (Internet Protocol Security): Operates at Network Layer. Two modes:
- Transport Mode: Only payload is encrypted (original IP header preserved). Used host-to-host.
- Tunnel Mode: Entire packet is encrypted and wrapped in a new IP header. Used site-to-site.
SSL/TLS VPN: Operates at Application Layer. User connects via browser (HTTPS). Common: OpenVPN, WireGuard (modern, fast, UDP-based).
WireGuard:Modern VPN protocol — simpler code (~4000 lines vs OpenVPN's 100,000), faster, uses modern cryptography (Curve25519, ChaCha20, Poly1305).
COMMON NETWORK ATTACKS
───────────────────────
Attack Layer Description
──────────────────────────────────────────────────────────────────────
DDoS 3/4/7 Overwhelms target with traffic from many sources
MITM (Man-in-Middle) 3/4/5 Intercepts communication between two parties
ARP Spoofing 2 Sends fake ARP messages to redirect traffic
DNS Spoofing 7 Corrupts DNS cache to redirect to malicious sites
Phishing 7 Tricks users into revealing credentials
SQL Injection 7 Inserts malicious SQL into application input
XSS 7 Injects malicious scripts into web pages
Packet Sniffing 1/2 Captures network traffic (use encryption to prevent)
MAC Flooding 2 Overwhelms switch CAM table causing it to act as hub
Rogue DHCP 7 Fake DHCP server assigns malicious config
Session Hijacking 4/7 Takes over an authenticated session
SSL Stripping 7 Downgrades HTTPS to HTTP (intercepts traffic)OSI Model has 7 layers (Physical, Data Link, Network, Transport, Session, Presentation, Application). It is a theoretical reference model developed by ISO for understanding and designing network architectures. TCP/IP Model has 4 layers (Link, Internet, Transport, Application) and is the practical model used by the Internet. The OSI Session and Presentation layers are merged into the TCP/IP Application layer. The OSI Data Link + Physical layers map to the TCP/IP Link/Network Access layer. The OSI Network layer maps to TCP/IP Internet layer. In interviews, you should know both and explain how real protocols map to OSI layers.
The 3-way handshake establishes a reliable connection: (1) Client sends SYN with sequence number x. (2) Server sends SYN-ACK with sequence number y and acknowledges x+1. (3) Client sends ACK acknowledging y+1.
Why not 2-way? A 2-way handshake cannot prevent duplicate/delayed SYN packets from establishing spurious connections. If an old SYN arrives, the server would ACK it, creating an invalid connection. The 3rd ACK ensures the server knows the client is alive and ready. This is called the two-army problem — you need mutual confirmation that both sides can send AND receive.
Step 1: Need 6 subnets. 2^n >= 6 -> n = 3 bits (2^3 = 8 subnets, 2 extra).
Step 2: Borrow 3 bits from host portion: new prefix = /27. Subnet mask = 255.255.255.224.
Step 3: Block size = 256 - 224 = 32.
Step 4: Hosts per subnet = 2^5 - 2 = 30.
Subnets:
Subnet 1: Network 192.168.10.0 | Range .1-.30 | Broadcast .31
Subnet 2: Network 192.168.10.32 | Range .33-.62 | Broadcast .63
Subnet 3: Network 192.168.10.64 | Range .65-.94 | Broadcast .95
Subnet 4: Network 192.168.10.96 | Range .97-.126 | Broadcast .127
Subnet 5: Network 192.168.10.128 | Range .129-.158 | Broadcast .159
Subnet 6: Network 192.168.10.160 | Range .161-.190 | Broadcast .191
Hub (Layer 1): A dumb device that repeats incoming signals to ALL ports. Creates a single collision domain and single broadcast domain. No intelligence, operates on electrical signals (bits). Half-duplex only.
Switch (Layer 2): An intelligent device that learns MAC addresses and forwards frames to the correct port. Each port is its own collision domain but all ports share one broadcast domain. Uses a CAM table (MAC address to port mapping). Full-duplex. Reduces unnecessary traffic.
Router (Layer 3): Routes packets between different networks based on IP addresses. Each interface is a separate broadcast domain. Has its own routing table. Can perform NAT, ACLs, inter-VLAN routing. TL;DR: Hub = broadcast everything; Switch = forward by MAC; Router = route by IP.
When you type www.example.com in your browser:
1. Browser Cache: Check if the IP is already cached by the browser.
2. OS Cache: Check the operating system's DNS resolver cache (e.g., /etc/hosts file).
3. Recursive Query to Resolver:OS sends a recursive query to the configured DNS resolver (usually your ISP's or a public one like 8.8.8.8).
4. Root Name Server: Resolver queries a root server (.), which responds with the TLD server for .com.
5. TLD Name Server: Resolver queries the .com TLD server, which points to the authoritative name server for example.com.
6. Authoritative Name Server: Resolver queries the authoritative server, which returns the A record (IP address).
7. Cache and Respond: Resolver caches the result and returns the IP to the browser.
Each server may cache results with a TTL (Time To Live) to speed up future queries.
This is the classic full-stack networking question covering multiple layers:
1. DNS Resolution: Browser resolves the domain name to an IP address (see Q5 above).
2. TCP Connection:Browser initiates a TCP 3-way handshake with the server's IP on port 443 (HTTPS).
3. TLS Handshake: Client and server perform SSL/TLS handshake to establish a secure encrypted connection.
4. HTTP Request: Browser sends an HTTP GET request (headers include User-Agent, Accept, Cookie, etc.).
5. Server Processing: Server receives request, routes to handler, queries database if needed, builds response.
6. HTTP Response: Server sends HTTP response (status code 200, headers, HTML body).
7. Browser Rendering: Browser parses HTML, builds DOM tree, fetches CSS/JS/images, executes JS, renders page.
8. TCP Termination: Connection is kept alive (Keep-Alive) or closed with 4-way FIN handshake.