TExcelTAD

DHCP

When you join a Wi-Fi network your device gets an IP address, a subnet mask, a default gateway and DNS servers, without you typing anything. That's DHCP (Dynamic Host Configuration Protocol, RFC 2131). A DHCP server leases addresses from a pool for a limited time.

DORA: the four-message exchange

Step Message From → To Meaning
D DHCPDISCOVER client 0.0.0.0:68 → broadcast 255.255.255.255:67 "Is there a DHCP server? I need an address."
O DHCPOFFER server → client "You can have 192.168.1.20 for 24 hours."
R DHCPREQUEST client → broadcast "I accept the offer from server 192.168.1.1." (broadcast so other servers withdraw their offers)
A DHCPACK server → client "Confirmed. Here's your mask, gateway and DNS."

The client has no IP address yet, so DHCP runs over UDP with broadcasts, and identifies the client by its MAC address and a random transaction ID (xid).

A DHCP server simulation

python · try it yourself
import ipaddress

class DhcpServer:
    def __init__(self, subnet, first, last, gateway, dns, lease_s=86400):
        self.net = ipaddress.ip_network(subnet)
        self.pool = [ipaddress.ip_address(first) + i
                     for i in range(int(ipaddress.ip_address(last)) - int(ipaddress.ip_address(first)) + 1)]
        self.gateway, self.dns, self.lease_s = gateway, dns, lease_s
        self.leases = {}          # mac -> ip
        self.offers = {}          # xid -> (mac, ip)

    def discover(self, mac, xid):
        ip = self.leases.get(mac)                         # returning client: same address
        if ip is None:
            taken = set(self.leases.values()) | {o[1] for o in self.offers.values()}
            free = [a for a in self.pool if a not in taken]
            if not free:
                return None
            ip = free[0]
        self.offers[xid] = (mac, ip)
        return {"type": "OFFER", "yiaddr": ip, "lease": self.lease_s}

    def request(self, mac, xid, ip):
        offer = self.offers.pop(xid, None)
        if offer != (mac, ip):
            return {"type": "NAK"}
        self.leases[mac] = ip
        return {"type": "ACK", "yiaddr": ip, "mask": self.net.netmask,
                "router": self.gateway, "dns": self.dns, "lease": self.lease_s}

def client_boot(server, mac, xid):
    print(f"{mac}  DISCOVER xid=0x{xid:08x}")
    offer = server.discover(mac, xid)
    if offer is None:
        print(f"{mac}  no OFFER: pool exhausted")
        return
    print(f"{mac}  OFFER    {offer['yiaddr']} for {offer['lease']}s")
    print(f"{mac}  REQUEST  {offer['yiaddr']}")
    ack = server.request(mac, xid, offer["yiaddr"])
    print(f"{mac}  {ack['type']:<8} {ack['yiaddr']}/{ack['mask']} gw {ack['router']} dns {ack['dns']}")

server = DhcpServer("192.168.1.0/24", "192.168.1.100", "192.168.1.102", "192.168.1.1", "192.168.1.1")
client_boot(server, "3c:22:fb:91:0a:7e", 0x3903F326)
client_boot(server, "b8:27:eb:12:34:56", 0x0A1B2C3D)
client_boot(server, "3c:22:fb:91:0a:7e", 0x77AA0001)     # reboot: same address again
client_boot(server, "08:00:27:4f:1c:22", 0x5E5E5E5E)
client_boot(server, "00:50:56:c0:00:08", 0x12345678)     # the pool has only 3 addresses
3c:22:fb:91:0a:7e  DISCOVER xid=0x3903f326
3c:22:fb:91:0a:7e  OFFER    192.168.1.100 for 86400s
3c:22:fb:91:0a:7e  REQUEST  192.168.1.100
3c:22:fb:91:0a:7e  ACK      192.168.1.100/255.255.255.0 gw 192.168.1.1 dns 192.168.1.1
b8:27:eb:12:34:56  DISCOVER xid=0x0a1b2c3d
b8:27:eb:12:34:56  OFFER    192.168.1.101 for 86400s
b8:27:eb:12:34:56  REQUEST  192.168.1.101
b8:27:eb:12:34:56  ACK      192.168.1.101/255.255.255.0 gw 192.168.1.1 dns 192.168.1.1
3c:22:fb:91:0a:7e  DISCOVER xid=0x77aa0001
3c:22:fb:91:0a:7e  OFFER    192.168.1.100 for 86400s
3c:22:fb:91:0a:7e  REQUEST  192.168.1.100
3c:22:fb:91:0a:7e  ACK      192.168.1.100/255.255.255.0 gw 192.168.1.1 dns 192.168.1.1
08:00:27:4f:1c:22  DISCOVER xid=0x5e5e5e5e
08:00:27:4f:1c:22  OFFER    192.168.1.102 for 86400s
08:00:27:4f:1c:22  REQUEST  192.168.1.102
08:00:27:4f:1c:22  ACK      192.168.1.102/255.255.255.0 gw 192.168.1.1 dns 192.168.1.1
00:50:56:c0:00:08  DISCOVER xid=0x12345678
00:50:56:c0:00:08  no OFFER: pool exhausted

The DHCP message format

DHCP messages reuse the older BOOTP layout: a 236-byte fixed part, the "magic cookie" 63 82 53 63, and then options in type-length-value form. Option 53 says which DHCP message this is.

python · try it yourself
import socket
import struct

def dhcp_discover(mac, xid):
    fixed = struct.pack("!BBBBIHH4s4s4s4s16s64s128s",
                        1, 1, 6, 0,             # op=request, htype=Ethernet, hlen=6, hops
                        xid, 0, 0x8000,         # xid, secs, flags (broadcast bit)
                        bytes(4), bytes(4), bytes(4), bytes(4),   # ciaddr yiaddr siaddr giaddr
                        bytes.fromhex(mac.replace(":", "")).ljust(16, b"\0"),
                        bytes(64), bytes(128))  # server name, boot file
    options = bytes([53, 1, 1])                 # DHCP message type = DISCOVER
    options += bytes([55, 3, 1, 3, 6])          # parameter request: mask, router, DNS
    options += bytes([255])                     # end
    return fixed + b"\x63\x82\x53\x63" + options

msg = dhcp_discover("3c:22:fb:91:0a:7e", 0x3903F326)
print(len(msg), "bytes")
print("first 12 bytes:", msg[:12].hex(" "))
print("chaddr:", msg[28:34].hex(":"))
print("cookie + options:", msg[236:].hex(" "))

def parse_options(data):
    i, out = 0, {}
    while data[i] != 255:
        code, length = data[i], data[i + 1]
        out[code] = data[i + 2:i + 2 + length]
        i += 2 + length
    return out

opts = parse_options(msg[240:])
names = {1: "DISCOVER", 2: "OFFER", 3: "REQUEST", 5: "ACK", 6: "NAK"}
print("message type:", names[opts[53][0]], "| requested options:", list(opts[55]))
249 bytes
first 12 bytes: 01 01 06 00 39 03 f3 26 00 00 80 00
chaddr: 3c:22:fb:91:0a:7e
cookie + options: 63 82 53 63 35 01 01 37 03 01 03 06 ff
message type: DISCOVER | requested options: [1, 3, 6]

Leases and renewal

A lease isn't forever. At T1 (50% of the lease) the client unicasts a REQUEST to renew with its server; if that fails, at T2 (87.5%) it broadcasts to any server; if the lease expires it must stop using the address.

python · try it yourself
lease = 86400       # 24 hours
t1, t2 = lease * 0.5, lease * 0.875
for name, t in [("obtained", 0), ("T1 renew (unicast)", t1), ("T2 rebind (broadcast)", t2), ("expiry", lease)]:
    h, rem = divmod(int(t), 3600)
    print(f"{name:<22} at {h:>2}h{rem // 60:02d}m")
obtained               at  0h00m
T1 renew (unicast)     at 12h00m
T2 rebind (broadcast)  at 21h00m
expiry                 at 24h00m

In the real world

bash
sudo dhclient -v eth0

Sample output:

text
DHCPDISCOVER on eth0 to 255.255.255.255 port 67 interval 3 (xid=0x3903f326)
DHCPOFFER of 192.168.1.20 from 192.168.1.1
DHCPREQUEST for 192.168.1.20 on eth0 to 255.255.255.255 port 67 (xid=0x3903f326)
DHCPACK of 192.168.1.20 from 192.168.1.1 (xid=0x3903f326)
bound to 192.168.1.20 -- renewal in 41328 seconds.
  • Relay agents: DHCP broadcasts don't cross routers. A router configured as a relay (ip helper-address on Cisco) forwards them to a central server and fills in giaddr so the server knows which subnet's pool to use.
  • Reservations: map a MAC to a fixed address, so a printer always gets the same IP.
  • No server? The host self-assigns a 169.254.x.x link-local address (APIPA). Seeing one is a strong hint that DHCP failed.
  • Rogue DHCP servers can hand out a malicious gateway or DNS server. Switches defend with DHCP snooping, which only trusts server replies from designated ports.

Go further: DHCP and Rogue DHCP Servers finds a rogue offer in a capture and covers DHCP snooping.

Test yourself

What is the correct order of DHCP messages?

  1. Request, Offer, Discover, Ack
  2. Discover, Offer, Request, Ack
  3. Discover, Request, Offer, Ack
  4. Offer, Discover, Ack, Request

Why does a DHCP client broadcast its DISCOVER?

  1. It is faster
  2. It has no IP address and doesn't know the server's address
  3. Broadcasts are encrypted
  4. Routers require it

A PC shows the address 169.254.33.7. What most likely happened?

  1. It got a public address
  2. DHCP failed and it self-assigned a link-local address
  3. It is using IPv6
  4. DNS is down