Network Layer & IP Protocol IP Datagrams, Connectionless Protocol, IPv4 vs IPv6

 

Network Layer & IP Protocol
Chapter 58 โ€” Part 2: IP Datagrams, Connectionless Protocol, IPv4 vs IPv6
๐Ÿ“š Theory
๐Ÿ’ป Code Examples
โ“ Interview Q&A

The Network Layer is responsible for getting your data from one machine to another โ€” even across thousands of routers spread across the globe. The protocol that does this job in the TCP/IP suite is IP (Internet Protocol). This page explains what IP does, what it does NOT do, and the difference between IPv4 and IPv6.

Key Concepts
Network Layer IP Protocol IPv4 IPv6 IP Datagram Connectionless Unreliable Best Effort Raw Socket SOCK_RAW SYN Flooding

๐ŸŒ What Does the Network Layer Do?

The network layer sits between the Transport layer (TCP/UDP) and the Data Link layer. Its three core responsibilities are:

โœ‚๏ธ
Fragmentation
Breaks large data into smaller pieces that fit the network’s MTU limit
๐Ÿ—บ
Routing
Decides which path each datagram takes across the internet to reach its destination
๐Ÿ”—
Services to Transport
Provides addressing and delivery services for TCP and UDP to use

The main protocol at this layer in the TCP/IP suite is IP โ€” Internet Protocol. Every device connected to the internet runs IP.

๐Ÿ”„ IPv4 vs IPv6 โ€” What Changed and Why

IPv4
โ˜‘ Address size: 32 bits
โ˜‘ ~4.3 billion addresses (theoretical)
โ˜‘ Practical addresses far fewer (poor allocation)
โ˜‘ Header checksum: YES
โ˜‘ UDP checksum: optional (but usually on)
โ˜‘ Min reassembly buffer: 576 bytes
โ˜‘ Max datagram: 65,535 bytes
โ˜‘ Introduced in BSD 4.2 (1983)
IPv6
โ˜‘ Address size: 128 bits
โ˜‘ 340 undecillion addresses
โ˜‘ Enough for every grain of sand on Earth
โ˜‘ Header checksum: REMOVED
โ˜‘ UDP checksum: mandatory
โ˜‘ Min reassembly buffer: 1500 bytes
โ˜‘ Max datagram: 65,575 bytes (+ jumbograms)
โ˜‘ Devised early 1990s, deployed gradually

The primary reason IPv6 was created was the exhaustion of IPv4 addresses. Because of the way addresses were structured and allocated historically, the ~4.3 billion address space ran out far sooner than expected.

๐Ÿ’ก Why is there no IPv5?
The IP header has a 4-bit version field. Version 4 = IPv4. Version number 5 was already assigned to an experimental protocol called Internet Stream Protocol (ST-II), designed for voice/video transmission in the 1970s. Since 5 was taken, the next version of IP was numbered 6.

๐Ÿ“ค IP Transmits Data as Datagrams

IP does not send a continuous stream of bytes. It sends individual, independent units called datagrams (also called packets). Each datagram is self-contained: it carries its own source and destination addresses in the header.

IP Datagram Structure
IP Header
Version (4 bits)
Header Length
Total Length
TTL
Protocol (TCP=6, UDP=17)
Header Checksum
Source IP Address
Dest IP Address
Fragment Offset
20โ€“60 bytes
IP Data (Payload)
Contains the TCP segment (or UDP datagram)
which in turn contains application data.

Max payload: up to 65,515 bytes (IPv4)
(65,535 total โˆ’ 20 byte header minimum)

Important: each datagram traveling from source to destination may take a completely different route through the internet. There is no guarantee they arrive in order. This is by design โ€” it makes the network resilient.

โš ๏ธ IP is Connectionless and Unreliable

These two properties are the most important things to understand about IP. They explain why TCP exists.

โŒ IP is Connectionless

IP does NOT establish a virtual circuit between sender and receiver before sending data. There is no “setup” phase. Each datagram is independent โ€” it is sent into the network and IP just tries its best to deliver it.

Compare to a phone call (connection-oriented): you must dial and connect before talking. IP is more like dropping letters in a mailbox โ€” each letter is independent.

โŒ IP is Unreliable (Best Effort)

IP makes a “best effort” but gives no guarantees:

  • Packets may arrive out of order
  • Packets may be duplicated
  • Packets may be lost entirely
  • Packets with header errors are silently discarded
  • No error recovery is performed by IP

This is not a flaw โ€” it’s a deliberate design choice. Keeping IP simple and fast allows it to handle enormous amounts of traffic. Reliability is the job of higher layers:

  • TCP adds reliability on top of IP (sequencing, retransmission, acknowledgements)
  • UDP applications can implement their own reliability if needed
๐Ÿ“Œ Checksums: IPv4 provides a header checksum (detects errors in the IP header only, not the data). IPv6 removed the IP header checksum entirely โ€” it relies on transport layer checksums (TCP/UDP) for error detection. TCP checksums are mandatory in both IPv4 and IPv6.

๐Ÿ”ง Raw Sockets (SOCK_RAW) โ€” Bypassing TCP/UDP

Normally, your application uses TCP (SOCK_STREAM) or UDP (SOCK_DGRAM), and the kernel handles the IP layer for you. But Linux also supports raw sockets (SOCK_RAW), which let your application communicate directly with the IP layer โ€” bypassing TCP and UDP entirely.

Normal Socket vs Raw Socket
Normal Socket
Your App
โ†“ uses
TCP or UDP
โ†“ uses
IP
โ†“
Data Link
Raw Socket
Your App
โ†“ bypasses TCP/UDP
TCP or UDP
โ†“ directly uses
IP
โ†“
Data Link

Raw sockets are used for tools like ping (uses ICMP via raw socket), traceroute, network scanners, and packet crafting tools. Creating raw sockets requires root privileges (CAP_NET_RAW capability).

/* raw_socket_example.c
 * Creates a raw socket at the IP level (requires root / CAP_NET_RAW)
 * This lets you send/receive IP datagrams directly,
 * bypassing TCP and UDP.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>   /* struct iphdr โ€” IP header */

int main(void)
{
    int raw_fd;

    /*
     * AF_INET  = IPv4
     * SOCK_RAW = bypass TCP/UDP; work directly with IP
     * IPPROTO_TCP = we want to see TCP packets
     *   (use IPPROTO_UDP for UDP, IPPROTO_ICMP for ICMP)
     */
    raw_fd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
    if (raw_fd == -1) {
        perror("socket(SOCK_RAW) โ€” are you root?");
        exit(EXIT_FAILURE);
    }
    printf("Raw socket created: fd=%d\n", raw_fd);

    /* With IP_HDRINCL option, we can build our own IP header */
    int opt = 1;
    if (setsockopt(raw_fd, IPPROTO_IP, IP_HDRINCL, &opt, sizeof(opt))) {
        perror("setsockopt IP_HDRINCL");
        close(raw_fd);
        exit(EXIT_FAILURE);
    }

    /*
     * Now you can recv() raw IP datagrams including the IP header.
     * struct iphdr gives you direct access to version, ttl, protocol,
     * src and dst addresses, etc.
     *
     * Note: Most application code uses SOCK_STREAM (TCP) or
     * SOCK_DGRAM (UDP) instead of SOCK_RAW.
     * Raw sockets are for specialized tools: ping, traceroute,
     * network scanners, custom protocol implementations.
     */

    char buf[65536];
    struct sockaddr_in src_addr;
    socklen_t addr_len = sizeof(src_addr);

    printf("Listening for raw IP packets (Ctrl+C to stop)...\n");
    while (1) {
        ssize_t n = recvfrom(raw_fd, buf, sizeof(buf), 0,
                             (struct sockaddr *)&src_addr, &addr_len);
        if (n < 0) { perror("recvfrom"); break; }

        struct iphdr *iph = (struct iphdr *)buf;
        printf("Got IP datagram: protocol=%d, total_len=%d, ttl=%d\n",
               iph->protocol, ntohs(iph->tot_len), iph->ttl);
    }

    close(raw_fd);
    return 0;
}
/* Compile and run as root:
   gcc -o raw_socket raw_socket_example.c
   sudo ./raw_socket
*/
โš ๏ธ Security note: A raw socket lets a user spoof (fake) the source IP address in a datagram. This is the foundation of SYN-flooding DDoS attacks โ€” the attacker sends TCP SYN packets with fake source IPs. Modern kernels have mitigations (SYN cookies) to handle this.

โ“ Interview Questions & Answers
Q1: What are the three main jobs of the network layer?
A: (1) Fragmentation โ€” breaking data into pieces small enough for the data link MTU. (2) Routing โ€” deciding the path a datagram takes across the internet. (3) Providing addressing and delivery services to the transport layer (TCP/UDP).
Q2: Why is IP described as “connectionless”?
A: Because IP does not establish any kind of virtual circuit or session before sending data. Each datagram is independent and self-contained. There is no handshake, no setup, no teardown at the IP level.
Q3: What does “best effort” delivery mean in the context of IP?
A: IP tries to deliver each datagram but makes no guarantee. Packets can be lost, duplicated, or arrive out of order. IP does not perform retransmission. If a router detects a header error, the packet is silently dropped. Reliability must come from TCP or the application itself.
Q4: What is the key difference between IPv4 and IPv6 in terms of address size?
A: IPv4 uses 32-bit addresses, giving ~4.3 billion possible addresses. IPv6 uses 128-bit addresses, giving 2^128 addresses โ€” astronomically more, effectively ending the address exhaustion problem. Both IPv4 and IPv6 support TCP and UDP.
Q5: Why does IPv6 remove the IP header checksum that IPv4 has?
A: To simplify and speed up IP processing at routers. Since TCP and UDP both have their own checksums (and UDP checksum is mandatory in IPv6), the IP header checksum is redundant. Removing it means routers do not need to recalculate it at every hop (the TTL field changes at every router, which would require recalculating the IPv4 checksum).
Q6: What is SOCK_RAW and when would you use it?
A: SOCK_RAW is a socket type that lets an application send and receive data directly at the IP layer, bypassing TCP and UDP. It requires root privileges. Use cases include: implementing ping (uses ICMP), implementing traceroute, network scanners (e.g., nmap), and custom protocol implementations.
Q7: What is a SYN flooding attack and how is IP’s address-spoofing capability involved?
A: In a SYN flood, an attacker sends huge numbers of TCP SYN packets using raw sockets, with fake (spoofed) source IP addresses. The victim server responds with SYN+ACK to non-existent addresses and waits for an ACK that never comes, exhausting its connection table. Modern kernels defend against this using SYN cookies โ€” the server avoids allocating state until the third handshake step is confirmed.
Q8: Why is there no IPv5?
A: The IP header contains a 4-bit version field. Version number 5 was already assigned to an experimental protocol called Internet Stream Protocol (ST-II), designed for multimedia transmission. So the next IP version was numbered 6.

Leave a Reply

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