Skip to lesson

OSI and TCP/IP models

"Explain the OSI model" opens many networking interviews, and the real test is whether you can place a device or protocol on the right layer without a pause. Layers give you one shared vocabulary for every later network question.

The seven OSI layers

The OSI model (Open Systems Interconnection) is a reference model that splits network communication into seven layers, numbered 1 to 7 from the wire upwards. Each layer does one job, uses the layer below and serves the layer above.

The first example lists the seven layers as a Java enum, with one job for each layer.

Example 1 · The seven layers as an enum

OsiLayersDemo.javaJava
enum OsiLayer {    PHYSICAL("bits on the wire or radio"),    DATA_LINK("frames to the next device, MAC addresses"),    NETWORK("packets across networks, IP addresses, routing"),    TRANSPORT("end-to-end delivery between programs, ports"),    SESSION("open, keep and close a conversation"),    PRESENTATION("data format, encoding, encryption"),    APPLICATION("protocols the app uses: HTTP, DNS, SMTP");
    final String job;
    OsiLayer(String job) {        this.job = job;    }}
public class OsiLayersDemo {    public static void main(String[] args) {        OsiLayer[] layers = OsiLayer.values();        for (int i = layers.length - 1; i >= 0; i--) {            System.out.printf("%d %-12s %s%n", i + 1, layers[i], layers[i].job);        }        StringBuilder mnemonic = new StringBuilder();        for (OsiLayer layer : layers) {            mnemonic.append(layer.name().charAt(0));        }        System.out.println("Bottom-up first letters: " + mnemonic);    }}
Output
7 APPLICATION  protocols the app uses: HTTP, DNS, SMTP
6 PRESENTATION data format, encoding, encryption
5 SESSION      open, keep and close a conversation
4 TRANSPORT    end-to-end delivery between programs, ports
3 NETWORK      packets across networks, IP addresses, routing
2 DATA_LINK    frames to the next device, MAC addresses
1 PHYSICAL     bits on the wire or radio
Bottom-up first letters: PDNTSPA

What this code does

  • The enum lists layers from 1 to 7, so array index + 1 is the layer number. The loop prints them top-down, the way they are usually drawn.
  • The first letters P D N T S P A are what "Please Do Not Take Sales People's Advice" helps you remember.

Layer 1 moves raw bits; layer 7 is what your app talks to. A common mnemonic from layer 1 to 7 is "Please Do Not Take Sales People's Advice": Physical, Data Link, Network, Transport, Session, Presentation, Application. From 7 down, use "All People Seem To Need Data Processing".

Three groups to remember:

  • Layers 1-3 (Physical, Data Link, Network) move data between machines: wires, neighbours, routes.
  • Layer 4 (Transport) moves data between two programs, end to end.
  • Layers 5-7 (Session, Presentation, Application) serve the app: conversations, formats, user-facing protocols.
OSI is a teaching model. Real protocols do not split cleanly into all seven layers, which is why the internet uses TCP/IP.

The TCP/IP model and how it maps to OSI

The TCP/IP model is the four-layer model the internet really runs on: Application, Transport, Internet and Network Access. Application covers OSI layers 5 to 7, Transport is 4, Internet is 3, and Network Access covers 1 and 2.

The second example maps each TCP/IP layer to the OSI layers it covers and prints them side by side.

Two stacks side by side. OSI has seven layers from Application at the top down to Physical. TCP/IP has four: Application covers OSI layers 5 to 7, Transport matches layer 4, Internet matches layer 3, Network Access covers layers 1 and 2. Example protocols: HTTP, TCP, IP, Ethernet.

Example 2 · Mapping TCP/IP layers to OSI layers

ModelMappingDemo.javaJava
import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
public class ModelMappingDemo {    public static void main(String[] args) {        Map<String, List<String>> tcpIpToOsi = new LinkedHashMap<>();        tcpIpToOsi.put("Application", List.of("Application", "Presentation", "Session"));        tcpIpToOsi.put("Transport", List.of("Transport"));        tcpIpToOsi.put("Internet", List.of("Network"));        tcpIpToOsi.put("Network Access", List.of("Data Link", "Physical"));
        int total = 0;        for (Map.Entry<String, List<String>> e : tcpIpToOsi.entrySet()) {            System.out.printf("%-15s -> %s%n", e.getKey(), String.join(" + ", e.getValue()));            total += e.getValue().size();        }        System.out.println(tcpIpToOsi.size() + " TCP/IP layers cover " + total + " OSI layers");    }}
Output
Application     -> Application + Presentation + Session
Transport       -> Transport
Internet        -> Network
Network Access  -> Data Link + Physical
4 TCP/IP layers cover 7 OSI layers

What this code does

  • A LinkedHashMap keeps insertion order, so the TCP/IP layers print top to bottom.
  • The top TCP/IP layer absorbs three OSI layers and the bottom one absorbs two; together the four cover all seven.

The model is named after its two main protocols, TCP and IP, and it describes how the internet works in practice, while OSI is the model used to explain and compare.

Some textbooks show a five-layer TCP/IP model with Physical and Data Link kept separate. Say which version you are using if the interviewer asks.

Encapsulation: data, segment, packet, frame, bits

Encapsulation means each layer wraps the data from the layer above with its own header (addresses or port numbers) before passing it down. The receiver reverses this, called decapsulation, and each layer removes its own header.

The example below wraps a UPI payment message layer by layer and prints what finally travels on the wire.

Example 3 · Encapsulation of a UPI payment message

EncapsulationDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class EncapsulationDemo {    public static void main(String[] args) {        String data = "PAY 250 TO ravi@upi";        List<String> steps = new ArrayList<>();
        String segment = "[TCP 52000->443]" + data;        steps.add("Transport adds ports      -> segment: " + segment);        String packet = "[IP 192.168.1.5->142.250.1.1]" + segment;        steps.add("Network adds IP addresses -> packet:  " + packet);        String frame = "[ETH aa:bb->cc:dd]" + packet + "[FCS]";        steps.add("Data Link adds MAC + FCS  -> frame:   " + frame);
        System.out.println("Data: " + data);        steps.forEach(System.out::println);        System.out.println("Physical sends the frame as " + frame.length() * 8 + " bits (8 per character here)");
        String received = frame.substring(frame.indexOf(']') + 1, frame.lastIndexOf('['));        received = received.substring(received.indexOf(']') + 1);        received = received.substring(received.indexOf(']') + 1);        System.out.println("After decapsulation: " + received);    }}
Output
Data: PAY 250 TO ravi@upi
Transport adds ports      -> segment: [TCP 52000->443]PAY 250 TO ravi@upi
Network adds IP addresses -> packet:  [IP 192.168.1.5->142.250.1.1][TCP 52000->443]PAY 250 TO ravi@upi
Data Link adds MAC + FCS  -> frame:   [ETH aa:bb->cc:dd][IP 192.168.1.5->142.250.1.1][TCP 52000->443]PAY 250 TO ravi@upi[FCS]
Physical sends the frame as 696 bits (8 per character here)
After decapsulation: PAY 250 TO ravi@upi

What this code does

  • Each layer puts its header in front of what it received: ports at transport, IP addresses at network, MAC addresses plus an FCS trailer (frame check sequence, an error check) at data link.
  • The receiver strips headers in the reverse order and gets back exactly the original data. Real headers are binary fields, not text; the text form is a simplified picture.

The unit at each layer has a name, the PDU (protocol data unit): data at Application, segment (TCP) or datagram (UDP) at Transport, packet at Network, frame at Data Link and bits at Physical.

Only the Data Link layer also adds a trailer, an error check at the end of the frame. The receiver reads and removes the headers in the opposite order.

Predict the output

Predict what goes on the wire

Each layer wraps the message it receives. Pick the final text.

String msg = "GET /results";
msg = "[TCP]" + msg;
msg = "[IP]" + msg;
msg = "[ETH]" + msg + "[FCS]";
System.out.println(msg);
Interview line: "Segment at layer 4, packet at layer 3, frame at layer 2, bits at layer 1."

Which devices and protocols work at each layer

The layer placement rule says a device or protocol belongs to the highest layer whose information it reads. A switch reads MAC addresses (layer 2), a router reads IP addresses (layer 3), and TCP and UDP read port numbers (layer 4).

The lookup example below places common devices and protocols on their layers, a favourite rapid-fire question.

Example 4 · Which layer? A quick lookup

LayerLookupDemo.javaJava
import java.util.Map;import java.util.TreeMap;
public class LayerLookupDemo {    public static void main(String[] args) {        Map<String, Integer> layerOf = new TreeMap<>();        layerOf.put("HTTP", 7);        layerOf.put("DNS", 7);        layerOf.put("TCP", 4);        layerOf.put("UDP", 4);        layerOf.put("IP", 3);        layerOf.put("ICMP", 3);        layerOf.put("Router", 3);        layerOf.put("Switch", 2);        layerOf.put("Ethernet", 2);        layerOf.put("Hub", 1);
        String[] asked = {"Switch", "Router", "ICMP", "DNS", "Hub", "UDP"};        for (String item : asked) {            System.out.println(item + " -> layer " + layerOf.get(item));        }    }}
Output
Switch -> layer 2
Router -> layer 3
ICMP -> layer 3
DNS -> layer 7
Hub -> layer 1
UDP -> layer 4

What this code does

  • A switch reads MAC addresses, so it is layer 2; a router reads IP addresses, so it is layer 3.
  • ICMP carries ping messages inside IP, which is why it is a network-layer protocol even though it feels like a tool.

HTTP, DNS, FTP and SMTP are application-layer protocols. TCP and UDP are transport. IP and ICMP (used by ping) are network. Ethernet and Wi-Fi are data link. Cables, hubs and repeaters are physical.

More placements:

  • Layer 1: cables, hubs, repeaters. Layer 2: switches, bridges, network cards (NICs).
  • Layer 3: routers. Layer 4: TCP, UDP and port numbers.
  • ARP sits between layers 2 and 3; it finds a MAC address for an IP address.
  • TLS (the S in HTTPS) is often placed at layer 6 or between 4 and 7; textbooks differ, so say "above TCP".

Find the bug

Find the wrong layer

Each note has one wrong line. Tap it, then check the fix.

A candidate places things on layers.

Round 1 of 3

Answering "Explain the OSI model" in an interview

Separation of concerns means each layer does one job and can change without breaking the others. It is the reason networks are layered: Wi-Fi can replace a cable at layers 1 and 2 and your browser does not notice.

A good answer has three parts: what the model is, the layers with one job each, and why layering helps. Keep it under a minute, then stop and let the interviewer ask more.

Text
"OSI is a seven-layer reference model for network communication.From the bottom: Physical sends bits, Data Link sends frames to thenext device using MAC addresses, Network routes packets with IP,Transport gives end-to-end delivery with TCP or UDP and ports,Session manages the conversation, Presentation handles format andencryption, and Application is where HTTP and DNS live.The internet actually uses the four-layer TCP/IP model, which mergesthe top three layers and the bottom two. Layering lets each partchange independently, like Wi-Fi replacing a cable."

Order of execution

Build the one-minute answer

Put the parts of a strong "Explain the OSI model" answer in order.

Next step

Check your understanding

12 quick questions