What Is DHCP? How Your Device Gets an IP Address Automatically

what is DHCP

You walk into a café, tap the Wi-Fi name, and within a second the web works. Nobody typed an address, picked a gateway or told your phone where to find a DNS server. Behind that second sits a short, polite conversation between your phone and a small piece of software called a DHCP server. This article walks through that conversation, step by step, with real examples and a simulation I ran to show what happens when it goes wrong.

The problem DHCP solves

Every device on a network needs an IP address, which is the number other devices use to send it data. If you set one by hand, you have to pick a number nobody else is using, enter the right subnet mask, the right gateway, and at least one DNS server. Get one digit wrong and the device either cannot talk to anyone or, worse, collides with another device and knocks it offline.

I have done this by hand on more machines than I care to count, back when a small office meant a spreadsheet of addresses taped inside the server cabinet. It works for ten machines. It collapses at a hundred, and it is hopeless for phones that join and leave a network several times a day.

The fix is DHCP, the Dynamic Host Configuration Protocol. A DHCP server owns a range of addresses and a set of settings. Any device that joins the network asks for them, receives a loan of one address, and uses it until the loan runs out. The key word is loan, and it explains almost everything else in this article.

The one-paragraph version. DHCP automatically gives a device an IP address and the other settings it needs (subnet mask, default gateway, DNS servers) when it joins a network. The exchange has four messages, nicknamed DORA: Discover, Offer, Request, Acknowledge. The address is leased for a limited time, and the device renews it before it expires. At home, your router is the DHCP server.

An everyday analogy: the hotel front desk

Picture a hotel with fifty rooms. You arrive with a suitcase and no room number. You do not walk the corridors trying doors. You go to the front desk, and the clerk checks which rooms are free, assigns you one, and hands over a key card that works until checkout. If you stay longer, you stop by the desk and extend it. If you leave without telling anyone, the key card simply stops working at checkout time and the room goes back into the pool.

Map it across: the hotel is the network, the rooms are IP addresses, the guest is your device, and the clerk is the DHCP server. The checkout time is the lease. That last detail matters more than it looks, and we will see why when the café runs out of rooms.

What exactly does a DHCP server hand out?

An IP address is only the headline. A device usually receives a small bundle of settings, delivered as numbered “options” inside the DHCP messages.

SettingExampleWhat it is for
IP address192.168.1.134Your device’s identity on this network.
Subnet mask255.255.255.0Tells the device which addresses are on the same local network.
Default gateway192.168.1.1The router that carries traffic out to the internet.
DNS servers192.168.1.1Where to look up names like example.com. At home, this is often the router itself, which forwards on.
Lease time24 hoursHow long the device may keep this address before renewing.

The ordinary home values above are only an example. Many routers use 192.168.0.x or 10.0.0.x instead, and lease times vary by manufacturer and by network. There are many more options (a domain name, time servers, boot file locations for network booting), but these five are the ones you will see in daily life.

The big question: how can you ask for an address when you have none?

Here is the puzzle that makes DHCP clever. Your phone has just joined the Wi-Fi. It has no IP address, no idea what the network looks like, and no idea where the DHCP server is. How do you send a message to someone you cannot address?

The answer is broadcast. The phone sends its first message from the address 0.0.0.0 (“I am nobody yet”) to 255.255.255.255 (“everybody on this local network”). It does not know who the server is, so it shouts to the whole room. Every device on the local network hears it, but only a DHCP server answers. DHCP runs over UDP, with clients using port 68 and servers using port 67.

DORA: the four-message conversation

Network engineers use the nickname DORA for the four steps. Here is the whole exchange.

CLIENTDHCP SERVER1 DISCOVERBroadcast: anyone have an address for me?2 OFFERServer: how about 192.168.1.134?3 REQUESTBroadcast: yes, I accept that offer4 ACKNOWLEDGEServer: confirmed, lease starts nowClient uses 0.0.0.0 until step 4. Client port 68, server port 67 (UDP).
The four DHCP messages. The first two are broadcast because the client has no address yet.

1. Discover

The client broadcasts: “Is there a DHCP server out there? I need an address.” The message carries the client’s hardware (MAC) address so the server knows who is asking.

2. Offer

A DHCP server picks a free address from its pool and replies: “I can lend you 192.168.1.134, with this mask, this gateway, these DNS servers, for 24 hours.” Notice it is an offer, not a grant. The address is held aside for the client, but the deal is not done.

3. Request

The client says: “Yes, I would like that address from that server.” This message is still broadcast, and that is deliberate. If two DHCP servers both made offers, the broadcast tells every server which offer the client accepted, so the others can release the address they had reserved.

4. Acknowledge

The server confirms: “It is yours.” Only now does the client configure its network interface with the address. The conversation takes a fraction of a second on a healthy network.

If you remember one thing: Discover and Request come from the client, Offer and Acknowledge come from the server. A common exam and interview trap is mixing up Offer (a proposal) with Acknowledge (the final confirmation).

The lease: an address is borrowed, not owned

When the server says “24 hours,” the clock starts. The client does not wait until the last second. It follows two timers defined in the DHCP standard (RFC 2131):

  • T1, the renewal time, defaults to 50 percent of the lease. The client quietly asks the same server, directly, to extend the lease.
  • T2, the rebinding time, defaults to 87.5 percent of the lease. If the original server has not answered, the client now broadcasts, asking any DHCP server to extend.
  • Expiry at 100 percent. If no server has answered, the client must stop using the address and start over with Discover.
Using the addressRenewing with the same serverAny server0 hLease granted12 hT1 renew (50%)21 hT2 rebind (87.5%)24 hExpiresLifetime of a 24-hour DHCP leaseRenewal success resets the clock. Failure at 24 h means the client must start over with Discover.
A 24-hour lease. Renewal is tried at 12 hours, rebinding at 21 hours, and the address must be given up at 24 hours.

On a normal network, renewal succeeds at the 12-hour mark and the lease clock resets. Your laptop can keep the same address for months without you noticing. The lease exists for the opposite case: devices that vanish. A phone that walks out of range never says goodbye, so the server needs a way to reclaim its address. That is what expiry does.

Let us build a tiny DHCP pool

Reading about leases is one thing. Seeing one is better. Here is a small address pool in Python that hands out addresses, renews them and reclaims expired ones. It is not a real DHCP server (there are no network packets), but it implements the same bookkeeping that real servers do.

import ipaddress
from collections import deque

class DhcpPool:
    """A tiny DHCP address pool: hand out, renew and reclaim leases."""
    def __init__(self, first, last, lease_seconds):
        a = int(ipaddress.IPv4Address(first))
        b = int(ipaddress.IPv4Address(last))
        self.free = deque(str(ipaddress.IPv4Address(i)) for i in range(a, b + 1))
        self.lease = lease_seconds
        self.leases = {}                     # mac -> (ip, expires_at)

    def reclaim(self, now):
        for mac, (ip, exp) in list(self.leases.items()):
            if exp <= now:
                del self.leases[mac]
                self.free.append(ip)         # reused last, like many servers

    def request(self, mac, now):
        self.reclaim(now)
        if mac in self.leases:               # renewal: same address, fresh clock
            ip = self.leases[mac][0]
        elif self.free:
            ip = self.free.popleft()
        else:
            return None                      # pool exhausted
        self.leases[mac] = (ip, now + self.lease)
        return ip

def timers(lease_seconds):
    """RFC 2131 defaults: renew at 50 percent, rebind at 87.5 percent."""
    return lease_seconds * 0.5, lease_seconds * 0.875

# demo
pool = DhcpPool("192.168.1.100", "192.168.1.102", lease_seconds=3600)
print("phone  ->", pool.request("aa:aa", 0))
print("laptop ->", pool.request("bb:bb", 10))
print("tv     ->", pool.request("cc:cc", 20))
print("tablet ->", pool.request("dd:dd", 30), "(pool is empty)")
print("phone renews at 1800s ->", pool.request("aa:aa", 1800))
print("tablet at 3700s ->", pool.request("dd:dd", 3700), "(laptop and tv expired)")
t1, t2 = timers(86400)
print("24h lease: renew at %.0fh, rebind at %.1fh" % (t1/3600, t2/3600))

Running it with a pool of only three addresses and a one-hour lease produces this:

phone  -> 192.168.1.100
laptop -> 192.168.1.101
tv     -> 192.168.1.102
tablet -> None (pool is empty)
phone renews at 1800s -> 192.168.1.100
tablet at 3700s -> 192.168.1.101 (laptop and tv expired)
24h lease: renew at 12h, rebind at 21.0h

Read it line by line. The first three devices get consecutive addresses. The tablet asks while the pool is empty and gets nothing, which is exactly what a real device experiences when a network runs out of addresses. The phone renews at the half-hour mark and keeps the same address. By 3,700 seconds, the laptop and TV leases have expired without anyone releasing them, so the tablet finally gets the laptop’s old address.

When the hotel runs out of rooms: a café simulation

Lease length sounds like a boring setting until you see it break something. So I simulated a café with Wi-Fi. About one new customer device joins every minute, stays for roughly half an hour on average, and leaves without telling the network. The DHCP pool has 100 addresses. I ran ten hours of café time, repeated twenty times with different random seeds, and varied only the lease length. Devices renew at the 50 percent mark while they are present, just like real ones.

Lease timePeak addresses in useDevices that could not get an address
10 min54 of 1000.0%
30 min71 of 1000.0%
1 hour95 of 1000.2%
4 hours100 of 10051.3%
24 hours100 of 10083.3%
0%25%50%75%100%0.0%10 min0.0%30 min0.2%1 hour51.3%4 hours83.3%24 hoursLease length (pool of 100 addresses, ten-hour café day, average of 20 runs)
Share of arriving devices that found the pool empty, by lease length. Same café, same crowd, same pool size.

The shape of the result is the lesson. With a 10 or 30-minute lease, nobody was turned away. At one hour, a handful of devices failed during the busiest moments. At four hours, about half of all arriving devices found no free address, and at 24 hours more than four out of five did. The crowd was identical in every run. The only difference was how long departed devices kept their addresses reserved.

The figures come from a simplified model: random arrivals, a random stay time and no early release. Real cafés have more variety, and the exact percentages will differ. The pattern will not. A short lease is the right tool for a transient crowd, and a long lease is the right tool for a stable one. Home and office networks, where the same devices come back every day, can use long leases comfortably. Hotels, airports, conferences and cafés should use short ones.

The same idea in five real settings

Click a tab to see DHCP in different places. Nothing to install and no page reload.

Home router

You buy a Wi-Fi router, plug it in and connect your phone, TV, laptop and a smart speaker. You never touch an address setting.

ServerYour router
Pool~100 addresses
LeaseOften 24 h
DNSRouter or ISP

How DHCP fits. The router runs a DHCP server by default, usually with a pool such as 192.168.1.100 to 192.168.1.199 (the exact range differs by brand). Long leases suit a home, because the same dozen devices come back every day. Look in the router’s admin page for a “connected devices” or “DHCP clients” list and you will see the leases.

Café or airport Wi-Fi

Hundreds of strangers pass through, most staying under an hour. Phones leave without any goodbye.

CrowdConstantly changing
LeaseMinutes to 1 h
PoolLarge
RiskPool runs dry

How DHCP fits. This is the café from our simulation. Public networks use short leases and wide pools so addresses of departed devices return quickly. Many also use much larger private ranges than a home network, because a /24 holds only 254 addresses.

Office with several networks

A company separates staff, guests, phones and printers into different networks for security and tidiness.

ServersOne central
RelayIP helper
ScopesOne per network
ExtrasReservations

How DHCP fits. Each network gets its own pool, called a scope, on one central DHCP server. Routers forward the broadcasts through a relay agent. Managers also add reservations for fixed gear and exclusion ranges so the pool never touches addresses set by hand.

Your ISP connection

Your home router does not come with an internet-facing address built in. It has to get one from your internet provider.

ClientYour router
ServerISP equipment
GetsWAN address
ChangesSometimes

How DHCP fits. On many cable and fibre connections, your router is itself a DHCP client on the provider’s side. It broadcasts a request, and the provider’s server leases it a public address. That is why a home address can change after a long outage. Other providers use different methods, such as PPPoE, so this varies by ISP.

Printer or NAS reservation

Your family prints from five devices. The printer is found by address, and every few weeks one laptop loses it.

DevicePrinter, NAS
Matched byMAC address
ResultFixed address
Set inDHCP server

How DHCP fits. A reservation tells the DHCP server: whenever this MAC address asks, always give it this address. The printer still uses DHCP, so nothing is typed on the device itself, but its address never moves. It is the tidiest way to get a stable address without hand-configuring anything.

Dynamic, static and reserved: three ways to get an address

DHCP is not all-or-nothing. Most real networks mix three approaches.

MethodHow the address is setBest forWatch out for
Dynamic DHCPServer picks any free address from the pool.Phones, laptops, guests, most devices.The address can change after a long absence.
DHCP reservationServer always gives the same address to a specific MAC address.Printers, NAS boxes, cameras, servers.Changing the network card changes the MAC, which breaks the match.
Static (manual)You type the address on the device itself.Routers, core infrastructure, bootstrapping.You must avoid the DHCP pool range or you risk conflicts.

My own rule after fifteen-odd years: configure a reservation on the DHCP server rather than a static address on the device whenever you can. All the addressing then lives in one place, and you can see and change it from the server. Static addresses scattered across devices are how networks accumulate mysteries.

What happens when DHCP fails?

If a device sends Discover and nobody answers, it does not give up silently. Modern operating systems fall back to a link-local address in the range 169.254.0.0 to 169.254.255.255 (defined in RFC 3927, and called APIPA on Windows). The device picks one at random in that range and checks that nobody else is using it.

That fallback only lets the device talk to other link-local devices on the same local network. There is no gateway, so there is no internet. If you ever open your network settings and see an address starting with 169.254, read it as a message: “I asked for an address, and nobody gave me one.”

Quick diagnosis. An address starting with 169.254 means DHCP did not respond. Check that the router is on, that you are on the right network, and that the DHCP service is enabled. Do not waste time hunting for DNS or website problems yet. You do not even have a valid address.

Commands you can run yourself

Seeing the lease on your own machine makes this concrete. The commands vary a little by operating system.

GoalWindowsLinux or macOS
See your current address and DHCP serveripconfig /allip addr (Linux), ipconfig getpacket en0 (macOS)
Give up the current leaseipconfig /releaseToggle the network interface off, or use your network manager’s reconnect option.
Ask for a new leaseipconfig /renewToggle the interface back on, or reconnect.

On Windows, ipconfig /all prints a “DHCP Server” line plus “Lease Obtained” and “Lease Expires” times. That is the lease we have been discussing, sitting right there on your screen. The macOS interface name (en0 here) can differ between machines, and Linux tools differ between distributions, so treat these as starting points.

Beyond one subnet: relay agents

There is an obvious catch with broadcasts. Routers do not forward them, so a DHCP broadcast stays inside its own local network. In a company with separate networks for staff, guests and printers, would you need a DHCP server in every one?

No. The trick is a DHCP relay agent, usually a setting on the router (often called “IP helper”). It listens for broadcasts on one network, wraps them in a unicast message and forwards them to a central DHCP server. The relay stamps in the address of the network the request came from, so the server knows which pool to use. One central server can then serve dozens of separate networks, each with its own address range.

Routerrelay agentStaff network10.1.0.0/24Guest network10.2.0.0/24Printer network10.3.0.0/24DHCP serverone central serverunicastBroadcasts stop at the router, so it forwards them to the server.The server picks the pool that matches the network each request came from.
A relay agent carries broadcasts from separate networks to one central DHCP server.

IPv6 and DHCPv6, briefly

Everything above is DHCP for IPv4. IPv6 networks have another automatic option called SLAAC (stateless address autoconfiguration), where a device builds its own address from information advertised by the router. DHCPv6 also exists, and networks use it when they want central control over addresses or need to pass out extra settings. The two are not rivals so much as tools, and many networks use them together. The details deserve their own article.

Security: DHCP trusts everyone

DHCP was designed for a friendlier era. A client believes the first offer it likes, with no authentication. That creates two classic problems.

Rogue DHCP servers

Someone plugs in a router, or a misconfigured device starts running a DHCP service. Clients that hear its offer first accept it, and now they receive a wrong gateway or a malicious DNS server. At best, people lose internet access and nobody can explain why. At worst, traffic is redirected through an attacker. The defence on managed switches is DHCP snooping, which only allows DHCP server messages from ports marked as trusted.

Address starvation

An attacker, or a buggy device, sends a flood of requests with fake MAC addresses until the pool is empty and real users get nothing. Switch features that limit the number of MAC addresses per port, and short leases on guest networks, reduce the damage.

Common problems and how I debug them

  • Two DHCP servers on one network. A very common home mistake is plugging a second router into the first one with its DHCP still enabled. Devices randomly get settings from either, and some end up with the wrong gateway. Turn off DHCP on one of them.
  • The 169.254 address. No reply from any server. Check cabling, Wi-Fi network, and whether the DHCP service is running.
  • Duplicate address warnings. A device with a manually typed address inside the DHCP pool range. Move the static address outside the pool, or create a reservation instead.
  • Pool exhaustion. Leases too long for the crowd, or the pool simply too small. Widen the range or shorten the lease, as in the café simulation.
  • The printer keeps “disappearing.” It got a new address after a long power-off. Give it a reservation.
  • Everything works by IP but not by name. The DHCP server handed out a bad DNS setting. Check the DNS option in the lease, not the website.

Common mistakes beginners make

  • Thinking DHCP and DNS are the same thing. DHCP assigns addresses. DNS translates names into addresses. DHCP merely tells you which DNS server to use.
  • Assuming a DHCP address is permanent. It is a lease. It often stays the same in practice, but nothing guarantees it.
  • Setting a static address inside the DHCP pool. The server may hand the same address to someone else.
  • Forgetting to exclude the router. The gateway itself should sit outside the dynamic range, typically at the start of the subnet.
  • Using a 24-hour lease on a public Wi-Fi network. You now know how that ends.

Test yourself

Tap a question to reveal the answer. The correct option is marked.

What are the four DHCP messages, in order?
  1. Request, Offer, Discover, Acknowledge
  2. Discover, Offer, Request, Acknowledge
  3. Discover, Request, Offer, Acknowledge
  4. Offer, Discover, Acknowledge, Request

Remember DORA: Discover and Request come from the client, Offer and Acknowledge from the server.

Why is the first DHCP message sent as a broadcast?
  1. Broadcasts are encrypted
  2. DHCP only works over TCP
  3. The client has no address and does not know where the server is
  4. Routers require it

With no address and no knowledge of the server, the client shouts to everyone on the local network and lets the server answer.

A lease is 8 hours. When does the client first try to renew, using the default timers?
  1. After 4 hours
  2. After 6 hours
  3. After 7 hours
  4. Only at 8 hours

T1 is 50 percent of the lease, so renewal begins at 4 hours. T2, the broadcast rebind, comes at 87.5 percent, or 7 hours.

Your laptop shows the address 169.254.37.12 and has no internet. What most likely happened?
  1. DNS is down
  2. The website is blocked
  3. The router is overheating
  4. No DHCP server answered, so it gave itself a link-local address

169.254.x.x is the link-local fallback used when DHCP does not respond. It allows only local-network chatter.

Which is the best way to give a network printer a stable address while managing everything centrally?
  1. A static address inside the DHCP pool
  2. A DHCP reservation tied to its MAC address
  3. A very short lease
  4. Turning DHCP off for the whole network

A reservation keeps the printer on DHCP but always gives it the same address, with no conflict risk and no manual typing on the device.

Frequently asked questions

What does DHCP stand for?

Dynamic Host Configuration Protocol. It automatically configures devices with an IP address and related network settings.

Is DHCP the same as DNS?

No. DHCP gives a device its address and tells it which DNS server to use. DNS is the separate service that turns names like example.com into addresses.

Will my device keep the same IP address?

Often yes in practice, because a returning device usually gets its old address back if it is still free. But a lease is not a guarantee. For a fixed address, use a DHCP reservation.

Where is the DHCP server on my home network?

In almost every case, it is your router. Some networks use a separate server or a dedicated device, and a home setup can have only one active DHCP server safely.

What happens if two DHCP servers are on one network?

Clients take whichever offer reaches them first, so devices get inconsistent settings, such as different gateways, and failures look random. Disable DHCP on one of the devices.

Should I use static IPs or DHCP?

Use DHCP for most devices. For devices that need a fixed address, prefer a DHCP reservation. Use true static addressing mainly for the router itself and a few core pieces of infrastructure, keeping those addresses outside the DHCP pool.

Key takeaways

  • DHCP automatically gives a device an IP address, subnet mask, gateway and DNS servers when it joins a network.
  • The four-step conversation is Discover, Offer, Request, Acknowledge. The first two are broadcast because the client has no address yet.
  • An address is a lease, not a gift. Clients renew at 50 percent of the lease and rebind at 87.5 percent.
  • Lease length should match the crowd. In my café simulation, a 30-minute lease turned nobody away, while a 24-hour lease turned away more than four in five devices.
  • Use reservations for printers and servers, keep static addresses outside the pool, and treat any 169.254 address as “DHCP did not answer.”
  • Relay agents let one server serve many networks, and DHCP snooping protects against rogue servers.
DHCPIP addressnetworking basicsDORADHCP leaserouterPython

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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