Networking Interview Prep
OSI Model

Physical, Data Link & Network Layers (Layers 1–3)

Physical, Data Link & Network Layers (Layers 1–3)

LinkedIn Hook

Most developers can name the 7 OSI layers. Almost none can explain why they exist.

Here is the honest answer: the OSI model is not about memorizing a list. It is about understanding how data physically leaves your machine, travels a few meters to a switch, and then — hop by hop — finds its way across the planet to a server you have never heard of.

Layers 1, 2, and 3 are where the magic starts:

  • Layer 1 (Physical) — your data becomes electrical pulses, light, or radio waves on a wire or in the air. No addresses. No structure. Just raw bits.
  • Layer 2 (Data Link) — your data gets wrapped in a frame with a MAC address. A switch on your local network reads only this layer to decide where to forward it. It does not care about the internet.
  • Layer 3 (Network) — an IP address gets attached. A router reads this layer, consults its routing table, and figures out the next hop toward the destination — even if that destination is 14 countries away.

These three layers answer a question that trips up junior developers in system design interviews every time: what is the difference between a switch and a router?

The answer is simpler than you think — and it is all about which OSI layer each device operates at.

Full lesson → [link]

#Networking #OSIModel #BackendEngineering #SystemDesign #InterviewPrep


Physical, Data Link & Network Layers (Layers 1–3) thumbnail


What You'll Learn

  • What each of Layers 1, 2, and 3 actually does — not just its name
  • The difference between bits, frames, and packets (the PDUs that define each layer)
  • Why switches and routers are fundamentally different devices that operate at different layers
  • How ARP bridges the gap between Layer 3 IP addresses and Layer 2 MAC addresses

The Analogy That Makes This Click

Think of sending a physical letter from your apartment to a friend in another city.

  • Layer 3 (Network) is the GPS navigation system. It knows your friend's city and plots a route across highways and cities. It thinks in terms of large logical addresses — like postal codes.
  • Layer 2 (Data Link) is the local delivery truck driver who knows your specific building and apartment number. Once the letter arrives in your friend's city, the driver handles the last-mile delivery using a local address — the MAC address of your specific machine.
  • Layer 1 (Physical) is the road and highway itself — the physical infrastructure (asphalt, cables, radio waves) that carries everything. The road does not know or care what is on the truck. It just provides the medium.

Each layer solves a different part of the delivery problem. Together they get the letter from your hands to your friend's hands.


Layer 1 — Physical

What It Does

Layer 1 is responsible for transmitting raw bits — ones and zeros — over a physical medium. It does not know what those bits mean. It does not know about addresses, errors, or structure. It is purely concerned with how signals travel from point A to point B.

The Signal Types

Your bits travel as one of three types of signals:

Signal TypeMediumExample
Electrical (voltage)Copper wireCat5e, Cat6 Ethernet cable
Light pulsesFiber optic cableData center backbone, ISP links
Radio wavesAirWi-Fi (802.11), Bluetooth, 4G/5G

Common Physical Media

  • Cat5e / Cat6 (UTP copper) — the standard Ethernet cable in most offices and homes. Cat6 supports up to 10 Gbps at short distances.
  • Fiber optic — uses light instead of electricity. Nearly immune to interference. Used for long-distance links (ISP backbone, undersea cables) and data center interconnects.
  • Coaxial cable — older cable used in cable TV and older cable internet. Still used in some HFC (Hybrid Fiber-Coaxial) networks by ISPs.
  • Wireless (radio) — Wi-Fi, cellular networks. The "cable" is invisible but Layer 1 still applies. Your wireless card converts bits to radio waves.

Bandwidth vs. Throughput

These two terms are not the same, and interviewers notice when you confuse them.

  • Bandwidth is the maximum theoretical capacity of a link — the width of the pipe. A Cat6 cable may support 1 Gbps bandwidth.
  • Throughput is the actual data transferred per second under real conditions — accounting for interference, congestion, protocol overhead, and retransmissions. Throughput is always less than or equal to bandwidth.

Think of bandwidth as a 6-lane highway and throughput as the number of cars that actually make it through per hour during rush-hour traffic.

Layer 1 Devices

  • Hub — a dumb repeater. Every bit that arrives on any port gets blasted out every other port. No intelligence, no filtering. Obsolete in modern networks but still appears in exam questions.
  • Repeater — amplifies or regenerates signals to extend cable length. No logic, just signal boosting.

PDU at Layer 1: Bit

The Protocol Data Unit (PDU) — the unit of data — at Layer 1 is the bit. There is no structure, no header, no address. Just a stream of 0s and 1s.


What It Does

Layer 2 takes raw bits from Layer 1 and organizes them into structured units called frames. It handles communication between devices on the same local network — the same LAN segment. It also provides basic error detection so that corrupted frames can be discarded.

The Two Sub-Layers

Layer 2 is officially split into two sub-layers by the IEEE:

  • LLC (Logical Link Control) — the upper sub-layer. Provides a common interface to Layer 3 protocols (IPv4, IPv6, etc.) and handles flow control and error notification (not correction).
  • MAC (Media Access Control) — the lower sub-layer. Handles the physical addressing (MAC addresses) and controls how devices on the same medium share access (CSMA/CD for Ethernet, CSMA/CA for Wi-Fi).

Most interview questions focus on the MAC sub-layer.

MAC Addresses

A MAC (Media Access Control) address is a 48-bit hardware address burned into every network interface card (NIC) at manufacture time. It looks like this:

00:1A:2B:3C:4D:5E
  • Written as 6 pairs of hexadecimal digits separated by colons (or hyphens)
  • The first 3 bytes (OUI — Organizationally Unique Identifier) identify the manufacturer
  • The last 3 bytes identify the specific device

MAC addresses are local. They are used only within a single network segment. Once a packet leaves your local network through a router, your MAC address is swapped out at every hop. The MAC address never crosses the internet — only IP addresses do.

Frames

A Layer 2 frame wraps the packet coming down from Layer 3 with:

  • Destination MAC address
  • Source MAC address
  • EtherType (tells the receiver which Layer 3 protocol is inside — 0x0800 for IPv4, 0x86DD for IPv6)
  • Payload (the Layer 3 packet)
  • FCS (Frame Check Sequence) — a CRC checksum at the end for error detection

Error Detection via CRC

The FCS field contains a CRC (Cyclic Redundancy Check) value. The sender runs a mathematical algorithm over the frame data and stores the result in FCS. The receiver runs the same algorithm and compares. If the values do not match, the frame is silently dropped. Layer 2 detects errors — it does not correct them. Correction is left to higher layers (TCP at Layer 4).

Switches

A switch is the primary Layer 2 device in a modern network. It is fundamentally different from a hub:

  • A switch maintains a MAC address table (also called a CAM table) that maps MAC addresses to the physical port on which they were learned.
  • When a frame arrives, the switch reads the destination MAC address and forwards the frame only to the port connected to that destination device.
  • If the switch does not know the destination MAC, it floods the frame out all ports except the one it arrived on — and listens for the reply to learn the mapping.

This makes switches far more efficient than hubs, because traffic is targeted, not broadcast to everyone.

ARP — Address Resolution Protocol

Here is the critical bridge between Layer 3 and Layer 2: ARP (Address Resolution Protocol).

When your machine wants to send data to an IP address on the same local network, it needs the destination's MAC address to build a Layer 2 frame. ARP resolves that:

  1. Your machine broadcasts an ARP Request: "Who has IP 192.168.1.10? Tell 192.168.1.1."
  2. The device with that IP responds with an ARP Reply: "192.168.1.10 is at MAC AA:BB:CC:DD:EE:FF."
  3. Your machine caches this mapping in its ARP table and uses that MAC address to build the frame.

ARP operates at the boundary of Layer 2 and Layer 3. It is technically a Layer 2 protocol (it does not use IP to deliver ARP messages) but it exists to serve Layer 3.

PDU at Layer 2: Frame

The PDU at Layer 2 is the frame.


Layer 3 — Network

What It Does

Layer 3 handles end-to-end logical addressing and routing — getting data from a source host to a destination host across multiple networks. While Layer 2 handles local delivery, Layer 3 handles the global journey.

IP Addresses

An IP address is a logical address assigned to a network interface. Unlike MAC addresses (which are hardware-burned and local), IP addresses:

  • Are assigned by administrators or DHCP
  • Can change (they are not permanently tied to hardware)
  • Are used to route traffic across the entire internet
  • Come in two versions: IPv4 (32-bit, e.g., 192.168.1.1) and IPv6 (128-bit, e.g., 2001:0db8::1)

IP addresses have a network portion and a host portion defined by the subnet mask. This hierarchy is what makes routing possible — routers make decisions based on network prefixes, not individual host addresses.

Packets

Layer 3 wraps the data from Layer 4 (e.g., a TCP segment) in a packet with an IP header containing:

  • Source IP address
  • Destination IP address
  • TTL (Time to Live) — decremented by 1 at each hop; when it reaches 0, the packet is dropped (prevents infinite loops)
  • Protocol — tells the receiver what Layer 4 protocol is inside (6 = TCP, 17 = UDP, 1 = ICMP)
  • Checksum — for header error detection

Routers

A router is the primary Layer 3 device. It operates on IP packets and makes forwarding decisions based on destination IP addresses.

A router connects multiple networks together. Your home router connects your local network (192.168.1.0/24) to your ISP's network. Your ISP's router connects to other ISPs. Every hop across the internet is a router making a forwarding decision.

Routing Tables

Every router maintains a routing table — a database of known network prefixes and the next hop (or interface) to use for each. A simplified routing table looks like this:

Destination        Next Hop         Interface
0.0.0.0/0          203.0.113.1      eth0       ← default route (internet)
192.168.1.0/24     directly         eth1       ← local LAN
10.0.0.0/8         10.10.10.1       eth2       ← internal corporate network

When a packet arrives, the router finds the longest prefix match in its table and forwards the packet accordingly. If no specific route matches, it uses the default route (0.0.0.0/0).

Hop-by-Hop Routing

Routing is not a single decision. It is a sequence of decisions made hop by hop:

  1. Your machine sends a packet destined for 93.184.216.34 (example.com)
  2. Your home router does not know how to reach that IP directly, so it forwards to your ISP's router
  3. Your ISP's router forwards to a transit provider's router
  4. Eventually a router that knows the route to 93.184.216.34's network forwards it directly
  5. At every step, a new Layer 2 frame wraps the same Layer 3 packet (because MAC addresses change at each hop, but IP addresses stay constant end-to-end)

This is the critical distinction: IP addresses stay the same end-to-end. MAC addresses change at every hop.

ICMP — Internet Control Message Protocol

ICMP lives at Layer 3. It is not used for data transfer — it is used for network diagnostics and error reporting.

  • ping sends an ICMP Echo Request and expects an ICMP Echo Reply
  • traceroute exploits the TTL field and ICMP Time Exceeded messages to map the route
  • When a router drops a packet (e.g., TTL expired, no route found), it sends an ICMP error back to the source

ICMP has no ports. It is not TCP or UDP. It is Layer 3 — it speaks in IP addresses, not port numbers.

PDU at Layer 3: Packet

The PDU at Layer 3 is the packet.


Code Example 1 — Simulating Encapsulation: IP Header + MAC Header

This Node.js example simulates how data gets encapsulated as it moves down from Layer 3 to Layer 2. In real networking this happens in the OS kernel — but modeling it in code makes the concept concrete.

// Simulate OSI encapsulation: Layer 3 (IP) → Layer 2 (Ethernet frame)

// Layer 4 payload (e.g., a TCP segment — simplified as a string here)
const tcpPayload = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n";

// Layer 3 — Add IP header (Network layer encapsulation)
function addIPHeader(payload, srcIP, dstIP, protocol = "TCP") {
  return {
    layer: "Layer 3 — IP Packet",
    header: {
      srcIP,
      dstIP,
      ttl: 64,
      protocol,
      version: "IPv4",
    },
    payload,
  };
}

// Layer 2 — Add Ethernet frame header (Data Link layer encapsulation)
function addEthernetFrame(ipPacket, srcMAC, dstMAC) {
  return {
    layer: "Layer 2 — Ethernet Frame",
    header: {
      dstMAC,
      srcMAC,
      etherType: "0x0800", // IPv4
    },
    payload: ipPacket,
    trailer: {
      fcs: computeCRC(JSON.stringify(ipPacket)), // simplified CRC
    },
  };
}

// Simplified CRC placeholder (real CRC uses polynomial division)
function computeCRC(data) {
  let crc = 0;
  for (const char of data) {
    crc = (crc ^ char.charCodeAt(0)) & 0xffffffff;
  }
  return crc.toString(16).padStart(8, "0");
}

// Simulate sending a request from your machine to a local gateway
const ipPacket = addIPHeader(
  tcpPayload,
  "192.168.1.5",   // your machine
  "93.184.216.34", // example.com
);

const ethernetFrame = addEthernetFrame(
  ipPacket,
  "AA:BB:CC:DD:EE:01", // your NIC's MAC address
  "AA:BB:CC:DD:EE:FE", // your router's MAC address (local gateway)
);

console.log("=== Encapsulated Frame ===");
console.log(JSON.stringify(ethernetFrame, null, 2));

// Key insight printed:
console.log("\n--- Key Insight ---");
console.log("Destination MAC:", ethernetFrame.header.dstMAC, "→ local router (changes at every hop)");
console.log("Destination IP: ", ethernetFrame.payload.header.dstIP, "→ final destination (stays constant end-to-end)");

What this shows:

  • The IP packet wraps the TCP payload with source/destination IP addresses
  • The Ethernet frame then wraps the IP packet with source/destination MAC addresses
  • The destination MAC is the local router — not example.com — because MAC addressing is local
  • The destination IP is example.com — it stays unchanged across all hops

Code Example 2 — ARP Table Lookup Simulation

This example simulates how a device resolves an IP address to a MAC address using an ARP table, and what happens when the entry is missing (triggering an ARP broadcast).

// Simulate ARP (Address Resolution Protocol) resolution
// ARP answers: "What MAC address owns this IP address?"

class ARPTable {
  constructor() {
    // ARP cache: IP → MAC mappings learned from the network
    this.table = new Map();
  }

  // Learn a mapping (this happens when an ARP Reply is received)
  learn(ip, mac) {
    this.table.set(ip, { mac, learnedAt: Date.now() });
    console.log(`[ARP] Learned: ${ip} → ${mac}`);
  }

  // Look up a MAC for a given IP
  resolve(ip) {
    const entry = this.table.get(ip);
    if (entry) {
      console.log(`[ARP] Cache hit: ${ip} → ${entry.mac}`);
      return entry.mac;
    }
    // Cache miss — need to broadcast an ARP Request
    console.log(`[ARP] Cache miss for ${ip} — broadcasting ARP Request...`);
    return this.broadcastARPRequest(ip);
  }

  broadcastARPRequest(targetIP) {
    // In a real network, this goes out as a broadcast frame:
    // Destination MAC: FF:FF:FF:FF:FF:FF (broadcast — all devices on LAN receive it)
    console.log(`[ARP] Sending: "Who has ${targetIP}? Tell 192.168.1.5"`);
    console.log(`[ARP] Broadcast MAC: FF:FF:FF:FF:FF:FF`);

    // Simulate receiving a reply from the target device
    const simulatedReply = this.simulateARPReply(targetIP);
    if (simulatedReply) {
      this.learn(targetIP, simulatedReply);
      return simulatedReply;
    }
    console.log(`[ARP] No reply — host ${targetIP} unreachable`);
    return null;
  }

  simulateARPReply(ip) {
    // Pretend these devices exist on our local network
    const networkDevices = {
      "192.168.1.1":  "AA:BB:CC:DD:EE:FE", // router/gateway
      "192.168.1.10": "11:22:33:44:55:66", // another PC
      "192.168.1.20": "99:88:77:66:55:44", // a printer
    };
    return networkDevices[ip] || null;
  }

  showTable() {
    console.log("\n=== ARP Table ===");
    if (this.table.size === 0) {
      console.log("(empty)");
      return;
    }
    for (const [ip, entry] of this.table) {
      console.log(`  ${ip.padEnd(16)} → ${entry.mac}`);
    }
    console.log("=================\n");
  }
}

// Usage
const arp = new ARPTable();

// Pre-populate one entry (as if we learned it earlier)
arp.learn("192.168.1.1", "AA:BB:CC:DD:EE:FE");

console.log("\n--- Resolving known IP (cache hit) ---");
arp.resolve("192.168.1.1");

console.log("\n--- Resolving unknown IP (ARP broadcast) ---");
arp.resolve("192.168.1.10");

console.log("\n--- Resolving unreachable IP ---");
arp.resolve("192.168.1.99");

arp.showTable();

// Why this matters:
// Before your machine can send a frame to 192.168.1.1 (your router),
// it must know the router's MAC address. ARP is how it finds out.
// Once learned, the result is cached so the broadcast is not repeated
// for every single packet — only when the cache entry expires (typically ~20 min).

What this shows:

  • ARP table acts as a local cache of IP-to-MAC mappings
  • A cache hit avoids the broadcast overhead
  • A cache miss triggers a broadcast (FF:FF:FF:FF:FF:FF) that every device on the LAN receives
  • ARP only works within a single subnet — you never ARP for an IP on a different network (you ARP for the gateway's MAC instead)

Physical, Data Link & Network Layers (Layers 1–3) visual 1


Common Mistakes

Mistake 1 — Confusing switches with routers

A switch operates at Layer 2 and uses MAC addresses to forward frames within a single LAN. A router operates at Layer 3 and uses IP addresses to forward packets between different networks. The distinction is not just about size or capability — it is about which layer they operate at and what addresses they read. A switch cannot route traffic to a different network. A router does not care about MAC addresses when making forwarding decisions.

Mistake 2 — Thinking MAC addresses route traffic across the internet

MAC addresses are local. They are used only within a single Layer 2 network segment. At every router hop, the packet gets unwrapped from its current frame, a brand-new frame is built with the next-hop router's MAC address, and the IP packet is put inside. By the time your packet reaches a server on the other side of the world, its source MAC address is the last router in the chain — not your laptop. MAC addresses never cross router boundaries.

Mistake 3 — Calling Layer 2 frames "packets" and Layer 3 packets "frames"

The terminology matters in interviews. The PDU at Layer 2 is a frame. The PDU at Layer 3 is a packet. Using "packet" as a generic term for everything shows imprecision. When explaining encapsulation or troubleshooting, using the right term signals that you understand what layer you are working at.


Interview Questions

Q: What is the difference between a switch and a router?

A switch is a Layer 2 device. It reads MAC addresses in Ethernet frames and forwards them within a single LAN. It does not understand IP addresses and cannot route traffic between different networks. A router is a Layer 3 device. It reads IP addresses in packets and makes forwarding decisions using its routing table to move traffic between networks — including across the internet. The key distinction is: switch = same network, MAC addresses; router = between networks, IP addresses.

Q: Why do MAC addresses change at every router hop, but IP addresses stay the same end-to-end?

IP addresses are the end-to-end logical addresses that identify the ultimate source and destination of traffic. They never change in transit (barring NAT). MAC addresses are local — they only make sense within a single LAN segment and the physical medium shared by devices on that segment. When a packet crosses a router, the router decapsulates the frame (discarding the Layer 2 header with the old MAC addresses), reads the IP destination, looks up the next hop, and builds a brand new frame for the next segment with new MAC addresses. This process repeats at every hop.

Q: What is ARP and why is it needed?

ARP (Address Resolution Protocol) resolves an IP address to a MAC address within a local network. It is needed because Layer 3 (IP) operates with logical addresses, but Layer 2 (Ethernet) operates with physical MAC addresses. To build an Ethernet frame you need the destination MAC address — and you do not always know it. ARP broadcasts a request on the LAN asking who owns a given IP. The owner replies with their MAC. Your machine caches the answer in its ARP table. Without ARP, your machine would not know how to address the Layer 2 frame even though it knows the IP destination.

Q: What is the difference between bandwidth and throughput?

Bandwidth is the theoretical maximum capacity of a network link — the size of the pipe. Throughput is the actual amount of data successfully transferred per unit of time under real-world conditions. Throughput is always lower than bandwidth due to protocol overhead, interference (especially on wireless), congestion, error-related retransmissions, and hardware limitations. For example, a Wi-Fi connection with 300 Mbps bandwidth might deliver only 150 Mbps of actual throughput in a busy environment.

Q: What happens at each layer when you run ping 8.8.8.8?

At Layer 3, an ICMP Echo Request packet is created with source IP (your machine) and destination IP (8.8.8.8). The TTL is set (e.g., 64). At Layer 2, your machine ARPs for the gateway MAC (if not cached), wraps the IP packet in an Ethernet frame addressed to the gateway's MAC, and sends it. At Layer 1, the frame is converted to electrical signals (or radio waves on Wi-Fi) and transmitted on the wire. At each router hop, the Layer 2 frame is stripped and rebuilt with new MAC addresses. When the ICMP packet reaches Google's server at 8.8.8.8, it sends an ICMP Echo Reply back through the same layer-by-layer process. Your terminal reports the round-trip time.


Quick Reference — Cheat Sheet

LayerNamePDUDevicesAddresses UsedKey ProtocolsKey Function
1PhysicalBitHub, Repeater, CableNoneEthernet (physical), 802.11 (Wi-Fi physical)Transmit raw bits as signals over a physical medium
2Data LinkFrameSwitch, Bridge, NICMAC address (48-bit hardware)Ethernet, Wi-Fi (802.11), ARP, PPPLocal delivery within a LAN; error detection via CRC
3NetworkPacketRouter, Layer 3 SwitchIP address (logical, 32-bit IPv4 / 128-bit IPv6)IPv4, IPv6, ICMP, OSPF, BGPEnd-to-end logical addressing; hop-by-hop routing between networks

Additional quick-reference notes:

  • Layer 1 signal types: electrical (copper), light (fiber), radio (wireless)
  • Layer 2 error detection: CRC in FCS field — detects errors, does not correct them
  • Layer 2 sub-layers: LLC (interface to Layer 3) + MAC (physical addressing, media access)
  • Layer 2 ARP: broadcast-based IP → MAC resolution, cached in ARP table
  • Layer 3 TTL: decremented by 1 at each router hop; packet dropped at TTL=0
  • Layer 3 ICMP: used by ping and traceroute; not TCP or UDP; no port numbers
  • MAC addresses: local only, change at every router hop
  • IP addresses: global logical addresses, constant end-to-end (except NAT)

Previous: Lesson 2.1 — OSI Model Overview → Next: Lesson 2.3 — Transport & Session Layers (Layers 4–5) →


This is Lesson 2.2 of the Networking Interview Prep Course — 8 chapters, 32 lessons.

On this page