IPv4 Packets
Every IP packet starts with a header that tells routers where it's going and how to handle it. In this lesson you build a real IPv4 header, compute its checksum the way routers do, and decode the fields.
The header
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-------+-------+---------------+-------------------------------+
|Version| IHL | DSCP/ECN | Total Length |
+-------+-------+---------------+-----+-------------------------+
| Identification |Flags| Fragment Offset |
+---------------+---------------+-----+-------------------------+
| Time to Live | Protocol | Header Checksum |
+---------------+---------------+-------------------------------+
| Source Address |
+---------------------------------------------------------------+
| Destination Address |
+---------------------------------------------------------------+| Field | Bits | Meaning |
|---|---|---|
| Version | 4 | always 4 |
| IHL | 4 | header length in 32-bit words (5 = 20 bytes, no options) |
| DSCP / ECN | 6 + 2 | priority class, congestion notification |
| Total Length | 16 | header + data in bytes (max 65,535) |
| Identification, Flags, Fragment Offset | 16 + 3 + 13 | fragmentation (see below) |
| TTL | 8 | decremented by each router; packet dropped at 0 |
| Protocol | 8 | what's inside: 1 = ICMP, 6 = TCP, 17 = UDP |
| Header Checksum | 16 | protects the header only |
| Source, Destination | 32 + 32 | IP addresses |
The Internet checksum
IPv4, ICMP, UDP and TCP all use the same simple Internet checksum (RFC 1071): add up the data as 16-bit big-endian words using one's complement arithmetic (carries wrap around), then invert the bits. A receiver adds up all the words, including the checksum, and should get 0xFFFF.
def internet_checksum(data: bytes) -> int:
if len(data) % 2:
data += b"\x00" # pad to a whole number of 16-bit words
total = 0
for i in range(0, len(data), 2):
total += (data[i] << 8) | data[i + 1]
total = (total & 0xFFFF) + (total >> 16) # wrap the carry around
return ~total & 0xFFFF
# An ICMP packet header from 10.0.0.5 to 10.0.0.1, checksum field set to 0
words = bytes.fromhex("4500 0054 0000 4000 4001 0000 0a00 0005 0a00 0001".replace(" ", ""))
print(hex(internet_checksum(words)))0x26a4
Building a header
import socket
import struct
def internet_checksum(data):
total = sum(struct.unpack(f"!{len(data) // 2}H", data))
while total > 0xFFFF:
total = (total & 0xFFFF) + (total >> 16)
return ~total & 0xFFFF
def ipv4_header(src, dst, payload_len, protocol, ttl=64, ident=0x1c46, dont_fragment=True):
version_ihl = (4 << 4) | 5
flags_frag = (0b010 << 13) if dont_fragment else 0
header = struct.pack("!BBHHHBBH4s4s", version_ihl, 0, 20 + payload_len, ident,
flags_frag, ttl, protocol, 0,
socket.inet_aton(src), socket.inet_aton(dst))
checksum = internet_checksum(header)
return header[:10] + struct.pack("!H", checksum) + header[12:]
hdr = ipv4_header("192.168.1.20", "93.184.215.14", payload_len=40, protocol=6)
print(hdr.hex(" "))
print("checksum field:", hdr[10:12].hex())
print("verify (should be 0):", internet_checksum(hdr))45 00 00 3c 1c 46 40 00 40 06 27 f3 c0 a8 01 14 5d b8 d7 0e
checksum field: 27f3
verify (should be 0): 0
Parsing a header
Here is the header of a DNS query packet (protocol 17 = UDP). Let's decode every field:
import socket
import struct
PROTOCOLS = {1: "ICMP", 6: "TCP", 17: "UDP", 58: "ICMPv6"}
raw = bytes.fromhex("45000038a1b2000040110d46c0a801140a000001")
(ver_ihl, tos, total_len, ident, flags_frag, ttl, proto,
checksum, src, dst) = struct.unpack("!BBHHHBBH4s4s", raw)
print("version: ", ver_ihl >> 4)
print("header bytes:", (ver_ihl & 0xF) * 4)
print("total length:", total_len)
print("id: ", hex(ident))
print("DF flag: ", bool(flags_frag & 0x4000), " MF flag:", bool(flags_frag & 0x2000))
print("frag offset: ", (flags_frag & 0x1FFF) * 8)
print("ttl: ", ttl)
print("protocol: ", proto, PROTOCOLS.get(proto))
print("checksum: ", hex(checksum))
print("src -> dst: ", socket.inet_ntoa(src), "->", socket.inet_ntoa(dst))version: 4
header bytes: 20
total length: 56
id: 0xa1b2
DF flag: False MF flag: False
frag offset: 0
ttl: 64
protocol: 17 UDP
checksum: 0xd46
src -> dst: 192.168.1.20 -> 10.0.0.1
TTL: stopping packets that loop
If routers are misconfigured, a packet could bounce between them forever. The Time To Live field prevents that: each router decrements it, and when it reaches 0 the router drops the packet and sends an ICMP "time exceeded" message back. Because the header changed, every router must also recompute the checksum.
import struct
def checksum(header):
total = sum(struct.unpack("!10H", header))
while total > 0xFFFF:
total = (total & 0xFFFF) + (total >> 16)
return ~total & 0xFFFF
header = bytearray.fromhex("45000038a1b200000311d6ffc0a801140a000001")
header[10:12] = struct.pack("!H", checksum(bytes(header[:10] + b"\0\0" + header[12:])))
for router in ["R1", "R2", "R3", "R4"]:
if header[8] <= 1:
print(f"{router}: TTL would hit 0 -> drop packet, send ICMP Time Exceeded")
break
header[8] -= 1
header[10:12] = b"\0\0"
header[10:12] = struct.pack("!H", checksum(bytes(header)))
print(f"{router}: TTL now {header[8]}, new checksum 0x{header[10:12].hex()}")R1: TTL now 2, new checksum 0x4b46
R2: TTL now 1, new checksum 0x4c46
R3: TTL would hit 0 -> drop packet, send ICMP Time Exceeded
The traceroute tool uses exactly this behaviour: it sends packets with TTL 1, 2, 3, … and lists the routers that report "time exceeded". Typical starting TTLs are 64 (Linux, macOS) and 128 (Windows), so a reply with TTL 56 probably came from a Linux server 8 hops away.
Fragmentation
If a packet is larger than the next link's MTU and the DF (Don't Fragment) flag is clear, a router splits it into fragments. Each fragment gets the same Identification, an offset (in 8-byte units) and the MF (More Fragments) flag, except the last. The destination reassembles them.
def fragment(total_payload, mtu, header=20):
max_data = (mtu - header) // 8 * 8 # fragment data must be a multiple of 8
offset = 0
while offset < total_payload:
size = min(max_data, total_payload - offset)
more = offset + size < total_payload
print(f"offset {offset:>4} (field {offset // 8:>3}) data {size:>4} MF={int(more)} "
f"packet {size + header} bytes")
offset += size
fragment(total_payload=4000, mtu=1500)offset 0 (field 0) data 1480 MF=1 packet 1500 bytes
offset 1480 (field 185) data 1480 MF=1 packet 1500 bytes
offset 2960 (field 370) data 1040 MF=0 packet 1060 bytes
Fragmentation is costly and fragile (losing one fragment loses the whole packet), so modern hosts set DF and use Path MTU Discovery instead: if a router replies "fragmentation needed", the sender uses smaller packets.
Go further: The IPv4 Header Byte by Byte parses a captured packet and checks headers for spoofing and fragment tricks.
Test yourself
What does a router do when it decrements a packet's TTL to 0?
- Resets it to 64
- Forwards it anyway
- Drops it and sends an ICMP Time Exceeded message
- Fragments it
Which Protocol field value means the IPv4 payload is TCP?
- 1
- 6
- 17
- 41
An IHL field value of 5 means the header is how long?
- 5 bytes
- 10 bytes
- 20 bytes
- 40 bytes