Knowledge

The OSI and TCP/IP models: the journey of a packet

Updated 2026-11-08 · Present

Estimated time: 40 minutes.

Quick summary

Step 1 — DNS — turning a domain name into an IP address

DNS (RFC 1034, RFC 1035) is the precondition for every connection that uses a hostname. The socket API receives a char* "example.com" through getaddrinfo() — the libc resolver reads /etc/nsswitch.conf, queries the DNS server (usually UDP :53, falling back to TCP :53 for responses >512 bytes — RFC 1035 §4.2.1), and parses the A record (IPv4) or AAAA (IPv6). The recursive mechanism: the stub resolver asks the local DNS (ISP/router), the local DNS asks the root (13 root servers, RFC 7720), the root returns the TLD (.com), the TLD returns the authoritative server (example.com's NS), and the authoritative server returns the A record. The result is cached according to the record's TTL. Response codes classify errors (RFC 1035 §4.1.1): NXDOMAIN (rcode=3, the name does not exist), SERVFAIL (rcode=2, the authoritative server failed), timeout (the resolver cannot be reached). DNS is not part of the packet journey of ping/curl once the resolve is done — but it is a mandatory step 0. Could not resolve host is ALWAYS a DNS failure, not the network. If dig example.com fails from the VPS → /etc/resolv.conf is wrong or a firewall blocks UDP :53.

When it breaks: Skipping the DNS lookup when debugging → you do not notice the DNS failure and assume it is a network error. 'Could not resolve host' is ALWAYS a DNS problem, not a cut cable. If you can ping the IP directly but pinging the domain fails = DNS is dead.

# Query DNS manually
dig example.com +short

# Or the older way
nslookup example.com

Observe with:

dig example.com +short — see the returned IP and the query time. If you only see SERVFAIL or no IP is returned, the DNS resolver has a problem. Try dig example.com @8.8.8.8 to bypass the ISP's resolver.

Symptoms when it breaks:

Fix:

  1. Check which DNS resolver is in use

    cat /etc/resolv.conf
    
  2. Bypass the ISP resolver and query 8.8.8.8 directly

    dig example.com @8.8.8.8 +short
    
  3. If the resolver is systemd-resolved, check its status

    systemd-resolve --status | grep 'DNS Servers'
    

Step 2 — Layer 4 Application: the ping command creates an ICMP echo request

The ping command is a userspace process that calls the syscall socket(AF_INET, SOCK_RAW, IPPROTO_ICMP) — unlike a TCP socket (SOCK_STREAM) or a UDP socket (SOCK_DGRAM). ICMP (RFC 792) is protocol number 1, sitting directly on IP — there is no concept of a port. The kernel creates an ICMP echo request (type=8, code=0) with an identifier + sequence number to match the reply; the payload is usually a timestamp + pattern bytes (default 56 bytes of data + 8 bytes of ICMP header = 64 bytes). It is sent down to the Internet layer. On Linux, a non-root user needs CAP_NET_RAW or the sysctl net.ipv4.ping_group_range to run ping. ICMP is at L3 (the Internet layer), not L4 (Transport). CLIs/UIs often group ping next to nc/curl — that is a tooling convention and does not reflect its position in the stack. The consequence: a passing ping does not imply a passing TCP :80 — a firewall may allow ICMP and block TCP (or vice versa).

When it breaks: Thinking ping tests the entire stack → skipping the TCP port test after a deploy. ICMP ping and TCP 80/443 are 2 different things. Firewalls often block ICMP while allowing TCP, or the reverse.

# Ping 4 packets then stop (Linux/Mac)
ping -c 4 example.com

# Windows
ping -n 4 example.com

Observe with:

ping -c 4 example.com — look at time= (RTT) and packet loss %. If loss is 0% and time is <100ms, the Internet layer is completely fine. If time is >500ms, there is a routing problem or the server is overloaded.

Step 3 — Layer 2 Internet: the OS encapsulates the IP header

The kernel wraps a 20-byte IP header (RFC 791 §3.1) around the ICMP payload. The important fields: Source IP (the outbound address of the interface chosen by the routing table), Destination IP (93.184.216.34 from DNS), Protocol=1 (ICMP), TTL=64 (the Linux default, RFC 1122 §3.2.1.7 recommends 64), Header Checksum (RFC 1071). TTL drops by 1 at every router (RFC 791 §3.2) — when TTL=0, the router drops the packet and sends an ICMP Time Exceeded (type=11) back to the sender. This is the principle traceroute exploits: send packets with TTL=1, 2, 3... to receive Time Exceeded from each hop. A packet is fragmented if its size > the path MTU (RFC 791 §3.2); the Linux kernel enables Path MTU Discovery by default (sysctl net.ipv4.ip_no_pmtu_disc=0, RFC 1191) to set the DF bit and avoid fragmentation. Understanding the IP header → you know how to debug: trace the Source IP being changed by NAT when it passes through a public router (the router replaces the Source IP with its own public IP, so the server sees the NAT box's IP, not the client's private IP). Misunderstanding private IPs (RFC 1918: 10/8, 172.16/12, 192.168/16) vs public → wrongly configured firewalls.

When it breaks: Not knowing your machine's IP = not knowing the Source IP in the packet = you cannot debug 'why does the server refuse the connection'. NAT changes the Source IP → the server sees an IP different from the client's. Confusing private and public IPs leads to wrong firewall configuration.

# See the machine's IP
ip addr show   # Linux
ifconfig       # Mac
ipconfig       # Windows

# See the routing table — where will the machine send packets?
ip route       # Linux
netstat -rn    # Mac
route print    # Windows

Observe with:

ip route get 8.8.8.8 — see which interface and gateway Linux picks to send a packet to 8.8.8.8. The output 'via X.X.X.X dev ethY src Z.Z.Z.Z' tells you the gateway, the NIC, and the source IP for this connection.

Step 5 — Across the Internet: routers forward by IP

A router receives the frame → checks the destination MAC (is it the router's own) → decapsulates Ethernet (strips the L2 header + FCS) → takes the IP packet → checks the destination IP → looks it up in the routing table (longest prefix match, RFC 1812 §5.2). The route entry points to an outgoing interface + a next-hop IP. The router decrements TTL by 1 and recomputes the IP header checksum (RFC 1071). The router resolves the next hop's MAC via ARP (if not cached) and builds a NEW Ethernet frame with destination MAC = the next hop's MAC and source MAC = the outgoing interface's MAC. It sends it out the NIC. This repeats at every router on the path to the server's network — the hop count can be verified directly with traceroute or mtr from a specific client. The key point: the IP header does not change across routers (except TTL + checksum), while the Ethernet header is RE-CREATED at every hop — because a MAC only has meaning within 1 broadcast domain. Understanding this → traceroute displays IPs (L3) not MACs (L2), and ping -r (record route option) displays the routers' IPs, not MACs.

When it breaks: Not knowing traceroute → when debugging 'why is latency high' or 'where are packets dropped' you can only look without finding the bottleneck. Traceroute reveals exactly which router is slow or dropping packets.

# See the real path, hop by hop
traceroute example.com     # Linux/Mac
tracert example.com        # Windows

# If traceroute stops halfway = a router on the path blocks ICMP/UDP
sudo traceroute -T -p 443 example.com

Observe with:

traceroute -n example.com (-n does not resolve hostnames, faster) — see the latency of each hop. If one hop suddenly jumps from 10ms to 200ms = the bottleneck is there. * * * = the router blocks ICMP, which does not mean it is down.

Step 7 — The reply comes back: ping prints '64 bytes from ... time=12.3 ms'

The client kernel receives the ICMP echo reply, matches the identifier + sequence against the request it sent, and computes RTT = receive timestamp − send timestamp (the timestamp lives in the payload, embedded by the kernel when sending). It updates the statistics (packets_received++) and passes the event up to the userspace ping process via recvmsg(). ping prints 64 bytes from 93.184.216.34: icmp_seq=1 ttl=54 time=12.3 ms. The fields: 64 bytes = ICMP + payload (not counting the IP header), ttl=54 = the TTL remaining when it reached the client (if the server sent TTL=64 → it passed 10 hops), time=12.3 ms = the round-trip RTT. The two most important metrics: packet loss % (after N packets, how many got no reply — 1-2% loss reduces TCP throughput because of retransmit window collapse, RFC 5681 §3.1) and jitter (RTT variation — jitter > 30 ms causes audio/video codec buffer underrun in realtime apps: VoIP, video calls, games). Pinging an IP on the same LAN (<1 ms expected) verifies local L1-L3; pinging an IP in another AS (<200 ms intercontinental fiber) verifies the WAN path.

When it breaks: Not knowing how to read ping output → you ignore the important packet loss and jitter. 1-2% packet loss on TCP cuts speed sharply (TCP retransmission). High jitter = instability, hurting video calls/realtime apps.

# Long-running ping to see jitter / packet loss
ping example.com

# Ping with a large size to test the MTU
ping -s 1472 example.com

Observe with:

ping -c 100 example.com — ping 100 packets to get accurate statistics. The end of the output has min/avg/max/mdev. A large mdev = high jitter = an unstable network. Packet loss > 0% = a serious problem.

Step 8 — Why can curl fail even though ping succeeds?

This is a test case that ties the whole stack together: ping tests L3 (ICMP echo), while curl/a browser tests L3 + L4 + L7. A successful ping proves L1→L3 are OK and the server kernel can reply. Curl needs more: L4 Transport (TCP, RFC 9293): a 3-way handshake to port 80/443 — SYN, SYN-ACK, ACK. A firewall blocking the port → "connection timeout" (the SYN gets no SYN-ACK). The host is up but no process listens on the port → "connection refused" (the kernel replies with a TCP RST). L7 Application (HTTP, RFC 9110): nginx/the app receives the TCP byte stream, parses the HTTP request, and returns a response. An nginx upstream failure → 502; an app crash → 500; a badly formatted client request → 400. Understanding this separation changes the debugging workflow completely: from "I can't reach the server" (vague) → "test each layer": ping (L3) → nc -vz host 443 (L4 + is the port open?) → curl -v (L7 + is the HTTP valid?). Knowing which layer fails tells you which tool to observe with (tcpdump for L3-L4, journalctl/the access log for L7).

When it breaks: Not knowing how to test each layer separately → when debugging you only know 'can't reach it' without knowing which layer the problem is at. Worse, you may restart the whole system for nothing when all you needed was to open a firewall port.

# Test the Transport layer on its own (no HTTP needed)
nc -vz example.com 443    # Linux/Mac
Test-NetConnection example.com -Port 443   # Windows PowerShell

# Test the Application too
curl -v https://example.com

Observe with:

nc -vz <ip_vps> 80 — if 'succeeded' = Transport OK, nginx is listening. If 'refused' = nginx has not started or the port is wrong. If it times out after 5-10s = a firewall is blocking port 80.

Common misconceptions

OSI Session/Presentation have no header of their own in the TCP/IP wire format — Application absorbs them into a single layer. That is why TCP/IP "merges into 4 layers" rather than dropping some. When debugging AWS ALB (L7) vs NLB (L4), this OSI-based distinction is a prerequisite for reading the docs correctly.

The concrete value: when you swap a copper cable for fiber, nginx does not recompile. When a client moves from WiFi to 4G, the TCP connection can be kept (with MPTCP) because L4 does not know L2 changed. This is an invariant, not theory.

A firewall can allow ICMP while blocking TCP :443. The host can be up and the kernel replying to ICMP — but if nginx has crashed, the client still gets 502 or connection refused. Ping only proves L1-L3 are OK and says nothing about L4-L7.

The physical constraint: the NIC only knows how to parse an Ethernet frame per IEEE 802.3 and does not know IP. If the order disappeared → the NIC would not know where a frame starts or ends. Understanding this invariant → when you see an unfamiliar packet capture (VXLAN, GENEVE), you know right away it is a tunnel overlay, not a "protocol that replaces TCP/IP".

Try it at home

1. The most basic command — check whether the target machine is alive + measure latency

ping -c 4 example.com

Observation: Look at time= (RTT) and packet loss. RTT <50ms = close, >200ms = far or slow. Packet loss > 0% is a worrying sign. Press Ctrl+C to stop, and ping will print the min/avg/max statistics.

2. Turn a domain name into an IP — the basis of every connection

dig example.com +short
# or
nslookup example.com

Observation: dig example.com +short prints only the IP, nothing more. Try dig example.com (without +short) to see the TTL and the server being used. If there is no output = DNS has failed completely.

3. See the machine's IP + MAC — know who the host is on the network

ip addr show       # Linux
ifconfig           # Mac
ipconfig /all      # Windows

Observation: Find the interface with state UP and an inet (IPv4) address. Take care to distinguish private IPs (192.168.x.x, 10.x.x.x, 172.16-31.x.x) from public ones. The MAC address is shown after 'ether' (Linux) or 'Physical Address' (Windows).

4. See the default gateway — the host's 'door out' to the internet

ip route           # Linux
netstat -rn        # Mac
route print        # Windows

Observation: Look for the line 'default via X.X.X.X' (Linux) or the '0.0.0.0' destination (Windows). The IP after 'via' is the gateway. Ping that gateway: if you cannot ping it = the Link/Internet to the gateway is dead = you cannot reach the internet.

5. See the real path of a packet through each router

traceroute example.com     # Linux/Mac
tracert example.com        # Windows

Observation: Each line is a router hop with its latency. Look for the point where latency suddenly jumps — that is the bottleneck. '* * *' does not mean down, only that the router does not reply to ICMP. The last hop = the destination server or close to it.

6. Tell 'connection refused' from 'timeout' by experiment — core debugging

# Refused: the machine is alive, nobody listens on the port
nc -vz 127.0.0.1 65000

# Timeout: the IP does not exist
nc -vz -w 3 203.0.113.254 80

Observation: nc -vz 127.0.0.1 65000 will report 'refused' immediately (<1s). nc -vz -w 3 80 will wait 3 seconds and then time out. The response speed is an important sign for telling them apart.

7. Watch packets in/out with tcpdump — a devops-level network debugging tool

sudo tcpdump -i any -n 'icmp' -c 10

Observation: While tcpdump is running, open another terminal and ping example.com. The output shows 2 lines per ping: 'echo request' (out) and 'echo reply' (back). Seeing only the request with no reply = a firewall blocks the return traffic.

Review questions

Question 1. When you type ping example.com, which layer of the 4-layer TCP/IP is NOT used?

  1. Link
  2. Internet
  3. Transport
  4. Application

Answer: Transport. ICMP (the protocol of ping) sits right at the Internet layer and does not go through Transport (TCP/UDP). That is why ping has no concept of a 'port'.

Question 2. You deploy an app to a VPS. From the client machine: ping <ip_vps> is OK, but curl http://<ip_vps> reports 'connection refused'. Which layer is the problem at?

  1. Link — the VPS network cable is loose
  2. Internet — wrong routing
  3. Transport — no process is listening on port 80
  4. Application — it returns 500

Answer: Transport — no process is listening on port 80. Ping OK = Link + Internet are OK, and the VPS is alive. 'Connection refused' = the TCP SYN arrived but the VPS kernel returned an RST because no process is listening on port 80. Possibly nginx is not running / is running on the wrong port.

Question 3. How do the 4-layer TCP/IP and the 7-layer OSI differ?

  1. TCP/IP is theory, OSI is what is actually deployed
  2. TCP/IP merges OSI's L5/L6/L7 into Application, and L1+L2 into Link
  3. They are exactly the same, only the names differ
  4. Both have 4 layers

Answer: TCP/IP merges OSI's L5/L6/L7 into Application, and L1+L2 into Link. The 4-layer TCP/IP = Application (merging OSI L5+L6+L7) + Transport (L4) + Internet (L3) + Link (L1+L2). This is the model that actually runs. OSI is a theoretical reference model.

Question 4. A host sends a frame out to the internet. What is the destination MAC address in the Ethernet frame?

  1. The destination server's MAC
  2. The gateway's MAC (the LAN router)
  3. Broadcast FF:FF:FF:FF:FF:FF
  4. The sending host's MAC

Answer: The gateway's MAC (the LAN router). A frame only travels within 1 LAN. To go outside it must rely on the gateway. ARP can only ask for a MAC within the LAN, so the first frame has destination MAC = the gateway's MAC. The gateway strips the frame and builds a new frame with the next hop's MAC.

Question 5. curl example.com reports 'could not resolve host'. Which layer is the problem at?

  1. Link — a loose cable
  2. Internet — IP routing is broken
  3. Application — DNS does not return an IP
  4. Transport — the TCP handshake fails

Answer: Application — DNS does not return an IP. DNS is a protocol at the Application layer. 'Could not resolve host' = curl could not obtain an IP → it never got as far as Internet/Transport. It is usually because the DNS server does not respond or /etc/resolv.conf is wrong.

Question 6. Why does TCP/IP separate Transport (ports) from Internet (IP)?

  1. For better security
  2. Because one machine has 1 IP but runs many services — ports distinguish nginx:80, ssh:22, mysql:3306
  3. Because routers need both the IP and the port to route
  4. Because IPv4 does not have enough ports

Answer: Because one machine has 1 IP but runs many services — ports distinguish nginx:80, ssh:22, mysql:3306. The very reason Transport exists is multiple services on 1 host. IP gets the packet to the right machine, the port gets the packet to the right process.

Question 7. You ping an IP and see a reply with ttl=54. What does this tell you?

  1. The packet has 54 seconds left to live
  2. The packet has passed through about 10 routers (if the destination OS sets the default TTL of 64)
  3. The connection can be held 54 more times
  4. It means nothing

Answer: The packet has passed through about 10 routers (if the destination OS sets the default TTL of 64). TTL decreases by 1 at each router. Many OSes set the initial TTL = 64 (Linux/Mac) or 128 (Windows). With ttl=54 at the client, guessing the server uses 64 → it passed 10 hops. This is a way to guess the OS type + the distance without traceroute.

Question 8. You unplug the network cable / turn off WiFi. Which error appears EARLIEST when you run curl?

  1. Connection timeout
  2. Could not resolve host (DNS fail)
  3. TLS handshake failed
  4. Network is unreachable — reported immediately

Answer: Network is unreachable — reported immediately. A Link layer failure is recognized by the kernel right away (the interface state is down). Curl asks the kernel to 'send' and the kernel replies 'there is no route' — there is nothing to wait for. The other errors all need a timeout or a response from outside.

Flashcards