Sub topic 7
Network layer: the IP header and end-to-end addressing
This chapter assumes you know what an IP address is, can read hexadecimal bytes, and have seen the transport layer's TCP and UDP headers from the previous chapter. Here you will study the IPv4 header field by field. You will also see why its addresses identify the two end hosts while link-layer addresses change at every hop.
What the network layer does
The transport layer hands down a segment (TCP) or datagram (UDP). The network layer wraps it in an IP header, and the result is a packet. The header carries what routers need to move the packet toward its destination:
- The source and destination IP addresses.
- A time-to-live counter that limits how long the packet can circulate.
- A protocol number that says what the payload is.
- Length and fragmentation fields.
- A checksum over the header itself.
IP is connectionless and gives best-effort delivery. A packet can be dropped, duplicated, delayed or reordered, and IP does not report it. Reliability, if you want it, comes from TCP or from the application.
The IPv4 header
The base header is 20 bytes. Options can extend it to at most 60 bytes, but they are rare in practice.
| Field | Size | Purpose |
|---|---|---|
| Version | 4 bits | Always 4 for IPv4 |
| IHL | 4 bits | Header length in 32-bit words (5 means 20 bytes) |
| DSCP / ECN | 8 bits | Traffic priority marking and congestion signalling |
| Total Length | 16 bits | Header plus payload, in bytes |
| Identification | 16 bits | Groups the fragments of one original packet |
| Flags | 3 bits | Includes Don't Fragment (DF) and More Fragments (MF) |
| Fragment Offset | 13 bits | Position of a fragment, in 8-byte units |
| TTL | 8 bits | Hop limit, decremented by each router |
| Protocol | 8 bits | What the payload carries |
| Header Checksum | 16 bits | Error check over the header only |
| Source Address | 32 bits | Sender's IP address |
| Destination Address | 32 bits | Receiver's IP address |
| Options | 0 to 40 bytes | Rarely used |
Three fields work together to frame the packet. IHL tells the receiver where the header ends, and Total Length tells it where the packet ends. The Protocol field tells it which handler gets the payload. Common protocol numbers are:
| Number | Payload |
|---|---|
| 1 | ICMP |
| 6 | TCP |
| 17 | UDP |
| 4 | An IPv4 packet (IP-in-IP tunnel) |
| 41 | An IPv6 packet |
The first byte of a typical header is 0x45: version 4 in the high nibble, IHL 5 in the low nibble. If you see 0x45 at the start of a hex dump, you are probably looking at an IPv4 packet with no options.
Reading the header in code
The following program builds a real header, fills in a valid checksum, and then parses it. It uses only the standard library.
import socket
import struct
def checksum(header: bytes) -> int:
"""Internet checksum: ones' complement sum of 16-bit words."""
total = 0
for i in range(0, len(header), 2):
total += (header[i] << 8) | header[i + 1]
while total >> 16:
total = (total & 0xFFFF) + (total >> 16)
return ~total & 0xFFFF
payload = b"hello"
src = socket.inet_aton("192.168.1.10")
dst = socket.inet_aton("203.0.113.5")
# Version 4, IHL 5, DSCP 0, total length, id, flags/offset 0x4000 (DF set),
# TTL 64, protocol 6 (TCP), checksum 0 for now, source, destination.
header = struct.pack("!BBHHHBBH4s4s", 0x45, 0, 20 + len(payload),
0x1234, 0x4000, 64, 6, 0, src, dst)
header = header[:10] + struct.pack("!H", checksum(header)) + header[12:]
# Parse it back.
ver_ihl, tos, total_len, ident, flags_frag, ttl, proto, csum, s, d = \
struct.unpack("!BBHHHBBH4s4s", header)
print("version:", ver_ihl >> 4)
print("header length:", (ver_ihl & 0x0F) * 4, "bytes")
print("total length:", total_len)
print("DF flag set:", bool(flags_frag & 0x4000))
print("fragment offset:", flags_frag & 0x1FFF)
print("TTL:", ttl, "protocol:", proto)
print("src:", socket.inet_ntoa(s), "dst:", socket.inet_ntoa(d))
print("checksum valid:", checksum(header) == 0)The last line prints True. The receiver does not compare checksums. It sums the whole header, checksum field included, and expects the result to be zero.
Addresses that identify the endpoints
The source and destination fields name the two hosts that are communicating. A router forwarding the packet reads the destination address, finds the matching route in its table, and sends the packet to the next hop. When several routes match, it uses the most specific one, the longest prefix. For example, a route for 203.0.113.0/24 beats a default route 0.0.0.0/0.
The IP source and destination normally stay the same from the sender to the receiver. The Ethernet addresses are different: they only name the two devices on one link, so they are rewritten at every router. The next chapters cover ARP and per-hop changes in detail. For now, remember this split:
- IP addresses describe the whole journey.
- MAC addresses describe one step of it.
Where the end-to-end rule breaks
Network address translation (NAT) rewrites the source address, and often the transport port, as packets leave a private network. A host at 192.168.1.10 appears on the internet as the router's public address. The destination sees the public address, so the IP header is no longer unchanged end to end. NAT also has to fix the TCP or UDP checksum, because that checksum covers a pseudo-header that includes the IP addresses.
TTL: protection against loops
Each router subtracts 1 from TTL before forwarding. If the result is 0, the router discards the packet and normally sends an ICMP "Time Exceeded" message to the source. Without this, a routing loop would keep a packet circulating forever.
traceroute uses this behaviour on purpose. It sends probes with TTL 1, 2, 3 and so on, and each router along the path reveals itself when it reports the expired probe.
Because a router changes TTL, it must also recompute the header checksum. That is a small per-hop cost, and it is one reason IPv6 dropped the header checksum entirely.
Fragmentation fields
If a packet is larger than the next link's MTU, a router may split it into fragments. Identification, the MF flag and Fragment Offset let the destination reassemble them. If the DF flag is set, the router drops the packet instead and sends back an ICMP "Fragmentation Needed" message. A later chapter covers MTU and MSS. For now, note that all of these fields live in the network layer header, and only the destination reassembles the fragments.
Common errors
- Treating the checksum as protection for the data. It covers only the IP header. Payload integrity is the job of the TCP or UDP checksum, plus the Ethernet frame check sequence.
- Reading IHL as bytes. It counts 32-bit words, so multiply by 4.
- Forgetting byte order. IP fields are big-endian (network order). Use
!instructformats, or you will see garbage values. - Assuming the source address is trustworthy. Nothing in IP verifies it, so a sender can forge it. This is why spoofed traffic is possible and why networks use ingress filtering.
- Assuming TTL is time. It started as a time limit, but it works as a hop count.
- Expecting IPv6 to look the same. IPv6 uses a fixed 40-byte header with a Hop Limit instead of TTL, a Next Header field instead of Protocol, 128-bit addresses, and no header checksum.
Practice
Exercise
A packet's first byte is 0x46. What are the IP version and the header length in bytes, and what does that tell you about the header?
Show answer
The high nibble is 4, so it is IPv4. The low nibble is 6, so IHL is 6 words, which is 24 bytes. The header is 4 bytes longer than the base 20-byte header, so it carries options.
Exercise
A packet leaves Host A with TTL 64 and crosses three routers on its way to Host B. Which IP header fields have changed when it arrives, and which have not?
Show answer
TTL is 61, and the header checksum was recomputed at each router. The source and destination addresses are unchanged, as are the Protocol field and the payload, assuming no NAT or fragmentation on the path. The Ethernet MAC addresses are not part of the IP header and were rewritten at every hop.