TCP/IP Protocol Layers & Encapsulation Sockets: Fundamentals of TCP/IP Networks

 

TCP/IP Protocol Layers & Encapsulation
Chapter 58 | Sockets: Fundamentals of TCP/IP Networks โ€” Part 1
๐Ÿ“š Theory + Diagrams
๐Ÿ’ป Code Examples
โ“ Interview Q&A

Before you write a single line of socket code, you need to understand how data actually moves from your application to the network wire โ€” and back. TCP/IP uses a layered model where each layer talks only to the layer directly above or below it. This page explains that layered architecture and the critical concept of encapsulation.

Key Concepts
Protocol Stack TCP/IP Layers Encapsulation Data Link Layer Network Layer Transport Layer Application Layer TCP Segment IP Datagram Data Frame

๐ŸŒ Why a Layered Architecture?

Networking is complex. You have hardware (cables, WiFi), addressing (IP), reliability (TCP), and your application โ€” all needing to work together. The layered approach solves this by giving each layer a single, well-defined job. Each layer uses the services of the layer below it and provides services to the layer above it.

Think of it like sending a letter through a courier company:

  • You write the letter (Application layer)
  • You put it in an envelope with an address (Transport layer adds port info)
  • The courier adds a routing label (Network layer adds IP address)
  • The truck physically carries it (Data link + physical medium)

Each step adds its own wrapper (header) around the data. This is encapsulation.

๐Ÿ“ˆ The Four TCP/IP Layers

The TCP/IP model has four layers. From top (closest to user) to bottom (closest to hardware):

๐Ÿ  Application Layer

HTTP, FTP, SSH, DNS, your app code
๐Ÿ”’ Transport Layer

TCP (reliable) / UDP (unreliable) โ€” port numbers
๐ŸŒŽ Network Layer

IP โ€” routing & IP addresses
๐Ÿ”Œ Data Link Layer

Ethernet, WiFi, PPP โ€” physical addressing (MAC)

Each layer on the sender side adds its own header. Each layer on the receiver side strips the corresponding header. This is called peer-to-peer communication โ€” logically, the TCP layer on your machine “talks” directly to the TCP layer on the remote machine, even though physically the data goes down through IP and Data Link first.

๐Ÿค Layered Communication โ€” How Two Hosts Talk

The diagram below shows how each layer on the source host communicates with the matching layer on the destination host. The arrows represent the logical (not physical) communication path.

Application
transfers application data
Application

โ†“
โ†‘

TCP
transfers TCP segments
TCP
โ†“
โ†‘

IP
transfers IP datagrams
IP
โ†“
โ†‘

Data Link
transfers data frames
Data Link
โ†“
โ†‘

๐Ÿ“ถ Network Medium (Cable / WiFi / Fiber)

Notice the arrows: data flows down the stack on the sender, through the network medium, and up the stack on the receiver.

๐Ÿ“ฆ Encapsulation โ€” Headers Wrapped Around Headers

When your application sends data, each layer wraps the data from the layer above inside its own structure, adding a header (and sometimes a trailer). This is called encapsulation. At the receiver, each layer strips its header and passes the inner data up. This is called de-encapsulation.

Application
sends:
Application Data

(e.g., HTTP request bytes)
= App payload

TCP
wraps:
TCP Header
src port, dst port,
seq#, ack#,
flags, checksum
Application Data
= TCP Segment

IP
wraps:
IP Header
src IP, dst IP,
checksum, TTL
TCP Header
App Data
= IP Datagram

Data Link
wraps:
Frame
Header

MAC addr
IP Hdr
TCP Hdr
Data
Frame
Trailer
= Data Frame

Key takeaway: by the time your 1KB application message hits the wire, it is wrapped inside a TCP header (~20 bytes), an IP header (~20 bytes), and a Data Link frame header/trailer. The receiver unwraps them in reverse order.

๐Ÿ“‹ What Each Header Contains

TCP Header (20+ bytes):

  • Source port number (16 bits)
  • Destination port number (16 bits)
  • Sequence number โ€” which byte in the stream this segment starts at
  • Acknowledgement number โ€” next byte expected from the other side
  • Flags: SYN, ACK, FIN, RST, PSH, URG
  • Checksum โ€” integrity check of header + data
  • Window size โ€” for flow control

IP Header (20 bytes minimum):

  • Source IP address (32 bits for IPv4)
  • Destination IP address (32 bits for IPv4)
  • Protocol field (6 = TCP, 17 = UDP)
  • TTL (Time To Live) โ€” decremented at each router; packet dropped at 0
  • Header checksum (IPv4 only)
  • Fragment offset (used when IP fragments a datagram)

Data Link Frame Header:

  • Source MAC address
  • Destination MAC address
  • EtherType (0x0800 = IPv4, 0x86DD = IPv6)

๐Ÿ’ป Code: Seeing the Layers in Action with a Simple TCP Socket

This C program creates a TCP client socket and connects to a server. Even though you only call send() once with your data, the kernel automatically wraps it in a TCP header, then an IP header, then a Data Link frame โ€” all transparently.

/* tcp_client.c - Simple TCP client demonstrating the layered model */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(void)
{
    int sockfd;
    struct sockaddr_in server_addr;
    const char *message = "Hello from EmbeddedPathashala!";
    char buffer[256];

    /*
     * Step 1: Create a TCP socket
     * AF_INET  = IPv4 (Network layer protocol)
     * SOCK_STREAM = TCP  (Transport layer protocol)
     * The OS will handle IP + TCP headers automatically
     */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }
    printf("Socket created: fd=%d\n", sockfd);

    /* Step 2: Fill in server address (IP + Port) */
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family      = AF_INET;
    server_addr.sin_port        = htons(8080);  /* port in network byte order */
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    /*
     * Step 3: connect() triggers the TCP 3-way handshake
     * SYN --> server
     * SYN+ACK <-- server
     * ACK --> server
     * Each of these goes through: TCP layer -> IP layer -> Data Link -> wire
     */
    if (connect(sockfd, (struct sockaddr *)&server_addr,
                sizeof(server_addr)) == -1) {
        perror("connect");
        close(sockfd);
        exit(EXIT_FAILURE);
    }
    printf("Connected to server\n");

    /*
     * Step 4: send() โ€” you pass only application data.
     * Kernel wraps it:
     *   [Data Link Header][IP Header][TCP Header][Your Message]
     * That whole bundle goes onto the wire.
     */
    ssize_t sent = send(sockfd, message, strlen(message), 0);
    printf("Sent %zd bytes of application data\n", sent);
    printf("(Actual bytes on wire = %zd + ~40 bytes of headers)\n",
           sent);

    /* Step 5: receive the reply */
    ssize_t n = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
    if (n > 0) {
        buffer[n] = '\0';
        printf("Received: %s\n", buffer);
    }

    close(sockfd);
    return 0;
}
/* Compile and run:
   gcc -o tcp_client tcp_client.c
   ./tcp_client

   To see the actual IP + TCP headers on the wire, use tcpdump:
   sudo tcpdump -i lo -n port 8080 -X
   The -X flag shows hex dump including all headers.
*/

Use tcpdump or Wireshark to actually see the encapsulation. You will see the Ethernet frame, then inside it the IP header with src/dst addresses, then the TCP header with ports and sequence numbers, then your data.

โ“ Interview Questions & Answers
Q1: What are the four layers of the TCP/IP model? What does each do?
A: Application (HTTP, FTP โ€” user protocols), Transport (TCP/UDP โ€” end-to-end delivery and port multiplexing), Network (IP โ€” routing and addressing), Data Link (Ethernet/WiFi โ€” local delivery using MAC addresses). Data flows down the stack on the sender and up the stack on the receiver.
Q2: What is encapsulation in TCP/IP networking?
A: Each layer wraps the data it receives from the layer above with its own header (and sometimes trailer). TCP adds a TCP header to form a segment. IP adds an IP header to form a datagram. Data Link adds a frame header/trailer. On the receive side, each layer strips its header (de-encapsulation) and passes the payload up.
Q3: What is the difference between a TCP segment, an IP datagram, and a data frame?
A: A TCP segment = TCP header + application data. An IP datagram = IP header + TCP segment. A data frame = Frame header + IP datagram + Frame trailer. Each is the unit of data at that particular layer.
Q4: Why does the application layer not know or care about IP addresses?
A: Because of the layered abstraction. The application layer only works with port numbers (and hostnames which DNS resolves). The socket API hides the IP/TCP details. The kernel’s TCP and IP code adds the necessary headers transparently when you call send() or write().
Q5: What information is in the TCP header?
A: Source port, destination port, sequence number (for stream ordering), acknowledgement number (for reliable delivery), control flags (SYN, ACK, FIN, RST, PSH, URG), window size (for flow control), and a checksum for integrity. The TCP header is at least 20 bytes.
Q6: What is the purpose of the TTL (Time To Live) field in the IP header?
A: TTL prevents packets from looping endlessly in the network due to routing bugs. Each router that forwards the datagram decrements the TTL by one. When TTL reaches zero, the router discards the packet and sends an ICMP “Time Exceeded” message back to the sender. This is how the traceroute tool works.
Q7: How does tcpdump help verify encapsulation?
A: tcpdump captures raw packets at the Data Link layer, so you can see the full encapsulated structure: Ethernet header, then IP header fields, then TCP header fields, then application payload โ€” confirming encapsulation happened exactly as the model describes.

Leave a Reply

Your email address will not be published. Required fields are marked *