Project 6: DHCP Client
A DHCP client that obtains an IP lease and prints configuration details.
Quick Reference
| Attribute | Value |
|---|---|
| Difficulty | Level 2: Intermediate |
| Time Estimate | Week |
| Main Programming Language | C |
| Alternative Programming Languages | Python, Go, Rust |
| Coolness Level | Level 3: Genuinely Clever |
| Business Potential | 1. The “Resume Gold” |
| Prerequisites | See concepts below |
| Key Topics | Naming and Configuration Services (DNS, DHCP, mDNS), IP Addressing, Subnetting, and Routing (Including NAT) |
1. Learning Objectives
- Build and validate: A DHCP client that obtains an IP lease and prints configuration details..
- Explain protocol behavior and verify it with a capture or trace.
- Handle edge cases and produce reproducible results.
2. All Theory Needed (Per-Concept Breakdown)
Naming and Configuration Services (DNS, DHCP, mDNS)
Fundamentals
Before a connection happens, a device needs two things: an address configuration and a name-to-address mapping. DHCP provides configuration: IP address, subnet mask, default gateway, and DNS servers. DNS provides name resolution: it turns a human-friendly name into IP addresses. On small local networks without an authoritative DNS server, mDNS and DNS-SD allow devices to discover services on the local link. These services are essential because users do not type IP addresses and devices do not manually configure themselves in modern networks.
Deep Dive
DNS is a hierarchical distributed database. When a client needs to resolve a name, it asks a recursive resolver (often provided by the ISP or a local router). The resolver performs iterative queries starting at the root, then the TLD, then the authoritative server for the zone. Responses are cached according to TTL values. This caching is why DNS queries can be fast, and also why changes can take time to propagate. DNS responses can arrive over UDP for small messages or TCP for larger responses or zone transfers. Understanding this distinction matters for debugging, since UDP truncation forces a TCP retry.
DHCP follows a discover-offer-request-acknowledge (DORA) exchange. A client with no address broadcasts a DHCPDISCOVER. A server replies with a DHCPOFFER. The client requests the offered address with DHCPREQUEST, and the server confirms with DHCPACK. Leases are time-limited and periodically renewed. This system allows dynamic reuse of addresses and centralized configuration. But it also introduces failure modes: multiple DHCP servers can fight, leases can expire if the server is unreachable, and clients can receive inconsistent options (like a wrong default gateway) that make the network appear partially broken.
mDNS and DNS-SD provide zero-configuration discovery. Instead of contacting a DNS server, devices send multicast queries to a well-known address on the local link. This allows discovery of printers, media devices, and local services without manual setup. The protocol reuses DNS message formats but changes the transport and scope. mDNS is powerful for home networks but can become noisy in larger environments. Understanding the scope and TTL settings for mDNS is essential when diagnosing why a device appears in a discovery list but is not reachable, or why service lists change frequently.
Naming and configuration services also intersect with security. DNS can be spoofed if you trust the wrong resolver or if a local attacker injects responses. DHCP can be abused by rogue servers. This is why managed networks often implement DHCP snooping and DNS security mechanisms. In home networks, the threat model is different, but the failure modes are similar. A misbehaving IoT device running a DHCP server can cause intermittent failures that look like random internet drops.
Finally, these services are the backbone of usability. When DNS or DHCP fails, users perceive that “the internet is down,” even if the physical link is fine. Your ability to build a DNS resolver or DHCP server from scratch is a demonstration that you truly understand how network configuration and naming work. It also makes you capable of implementing local overrides like DNS sinkholes, which are highly practical for security and ad-blocking.
How this fit on projects Projects 5-8, 10, and 16 are direct applications of DNS, DHCP, and mDNS.
Definitions & key terms
- Resolver: The client-side DNS component that asks questions.
- Recursive resolver: DNS server that walks the hierarchy on behalf of clients.
- TTL: Time-to-live for cached DNS answers.
- Lease: The time a DHCP address is valid.
- mDNS: Multicast DNS on a local link.
Mental model diagram
Client -> Resolver -> Root -> TLD -> Authoritative
^ cache TTLs at each step
How it works
- Client obtains an IP address and DNS server via DHCP.
- Client asks resolver for a name.
- Resolver walks the DNS hierarchy and caches answers.
- Local devices use mDNS for link-local discovery. Invariants: DNS is cached and hierarchical. Failure modes: rogue DHCP, stale DNS cache, mDNS storms.
Minimal concrete example
DNS query/response (text):
Query: A example.com
Answer: example.com -> 93.184.216.34 (TTL 86400)
Common misconceptions
- “DNS is always real-time.” It is cached by design.
- “DHCP only gives IP addresses.” It also provides gateway and DNS servers.
Check-your-understanding questions
- Why might a DNS change take hours to show up?
- What happens if a DHCP lease expires and the server is down?
Check-your-understanding answers
- Cached answers remain valid until TTL expires.
- The client may lose connectivity or fall back to a self-assigned address.
Real-world applications
- Local ad-blocking via DNS sinkholes.
- Zero-configuration printer discovery.
Where you will apply it
- Projects 5-8, 10, 16
References
- RFC 1034/1035 (DNS), RFC 2131 (DHCP)
- RFC 6762/6763 (mDNS, DNS-SD)
Key insights Naming and configuration are invisible until they fail, then everything fails.
Summary DNS and DHCP are the core control plane of a home network.
Homework/Exercises to practice the concept
- Trace a DNS lookup from your device to the authoritative server.
- Capture a DHCP DORA exchange and label each step.
Solutions to the homework/exercises
- Use
dig +traceand note each delegation. - Filter UDP ports 67 and 68 and identify discover, offer, request, ack.
IP Addressing, Subnetting, and Routing (Including NAT)
Fundamentals
IP is the addressing and routing system of the internet. IPv4 uses 32-bit addresses and relies on subnet masks (CIDR) to determine which destinations are local versus remote. Your device sends local traffic directly and remote traffic to the default gateway (your router). Routing is a hop-by-hop decision made by routers using the longest prefix match in the routing table. NAT (Network Address Translation) is common at the edge: it maps many private addresses to a single public address. Subnetting is the tool that partitions a network into smaller segments, which is critical for performance, security, and scaling in home/office environments.
Deep Dive
An IP address has two parts: the network prefix and the host identifier. CIDR notation (for example, /24) tells you how many bits belong to the prefix. The prefix defines the boundary of local delivery. If the destination IP shares the same prefix, the host uses ARP to find the destination MAC and sends directly. If not, it sends to the default gateway. This simple rule explains most “why can’t I reach this device” problems. Subnetting is the practice of choosing a prefix length that fits your network size and segmentation goals. Too large a subnet creates unnecessary broadcast traffic and larger failure domains. Too small a subnet causes address shortages or awkward routing rules.
Routing decisions are made by examining the destination IP and finding the most specific (longest) match in the routing table. A default route (0.0.0.0/0) catches everything else. Each router decrements the TTL field, which prevents routing loops from persisting forever. When TTL reaches zero, the router drops the packet and sends an ICMP Time Exceeded message. This is the mechanism that traceroute exploits. In home networks, your router usually has a handful of routes: the local LAN, perhaps a guest LAN, and a default route to your ISP. But in small office networks, you might add static routes to reach a lab subnet, or a VPN route to reach a remote office. Misconfigured routes cause asymmetric paths, which are hard to debug without captures.
NAT adds a stateful translation table at the edge. It replaces private source IPs and ports with a public IP and a chosen source port (often called PAT). When replies come back, the router uses this table to translate them back to the internal host. This is how many devices share one public address. NAT also breaks the original end-to-end model of the internet, which is why inbound connections typically require explicit port forwarding. Understanding NAT is critical for troubleshooting “I can browse the web but cannot host a server” issues, and for understanding why some peer-to-peer applications struggle. NAT is not a firewall, but it has similar observable effects because unsolicited inbound traffic is dropped by default when no translation table entry exists.
IPv6 changes the addressing landscape. It uses 128-bit addresses, removing the need for NAT at the edge. Instead of ARP, IPv6 uses Neighbor Discovery (ND). IPv6 hosts often use Stateless Address Autoconfiguration (SLAAC) to build their own addresses from router advertisements. In practice, many home networks operate dual-stack (IPv4 and IPv6). This means troubleshooting can involve two parallel protocol stacks, with different failure modes. A device might fail over IPv4 but work over IPv6, or the reverse. Understanding IP addressing at both versions makes you far more effective at diagnosing real-world issues.
Finally, routing and addressing are where policy is enforced. VLANs map to IP subnets. Firewall rules frequently reference IP ranges. VPNs create new routes. If you know how to design and reason about addresses and routing tables, you can predict how traffic will flow before you even run a packet capture. That ability is what transforms you from a user of networks into an engineer of networks.
How this fit on projects Subnet math and routing logic are required for Projects 1-3, 9, 14, 18, and 19.
Definitions & key terms
- CIDR: Prefix notation for networks (e.g., /24).
- Default gateway: Router used for off-subnet traffic.
- Longest prefix match: Routing rule that chooses the most specific route.
- NAT/PAT: Translation of internal addresses to a public address with ports.
Mental model diagram
LAN 192.168.1.0/24 Router/NAT Internet
Host 192.168.1.50 -> [NAT table] -> 203.0.113.5:45001
How it works
- Host checks if destination is in local subnet.
- If local, ARP and send directly; if not, send to gateway.
- Router chooses route via longest prefix match.
- NAT rewrites source IP/port for outbound flows. Invariants: TTL always decrements at routers. Failure modes: wrong subnet mask, missing default route, NAT table exhaustion.
Minimal concrete example
Routing table snippet:
192.168.1.0/24 -> eth0 (direct)
0.0.0.0/0 -> 192.168.1.1 (default)
Common misconceptions
- “Two devices with the same IP will work if they are on different switches.” They will conflict if on the same subnet.
- “NAT protects me from all inbound attacks.” It does not replace a firewall.
Check-your-understanding questions
- Why does a /24 network have 254 usable addresses?
- What happens when no route matches a destination?
Check-your-understanding answers
- Two addresses are reserved: network and broadcast.
- The packet is dropped (and often an ICMP unreachable is sent).
Real-world applications
- Planning guest and IoT subnets.
- Diagnosing port forwarding and inbound access problems.
Where you will apply it
- Projects 1-3, 9, 14, 18, 19
References
- “TCP/IP Illustrated, Vol 1” by Stevens - Ch. 3
- RFC 791 (IPv4), RFC 8200 (IPv6)
Key insights Addressing and routing are the map; NAT and policy are the gatekeepers.
Summary If you can compute subnets and read routing tables, you can predict traffic flow.
Homework/Exercises to practice the concept
- Divide 192.168.10.0/24 into four /26 subnets.
- Sketch a routing table for a network with a guest VLAN and a VPN.
Solutions to the homework/exercises
- /26 blocks at .0, .64, .128, .192.
- Include routes for each subnet plus a default route to the ISP.
3. Project Specification
3.1 What You Will Build
A DHCP client that obtains an IP lease and prints configuration details.
Included:
- CLI tool with clear output
- Validation steps and logging
- Documentation of assumptions
Excluded:
- Production-grade performance tuning
- Full security hardening
3.2 Functional Requirements
- Core function: Implement the primary behavior described in the project goal.
- Observable output: Produce deterministic output comparable to the Real World Outcome.
- Error handling: Handle timeouts, invalid inputs, and unreachable hosts gracefully.
3.3 Non-Functional Requirements
- Performance: Complete typical tasks within a few seconds on a LAN.
- Reliability: Fail safely and clearly on errors.
- Usability: Provide concise CLI flags and helpful messages.
3.4 Example Usage / Output
$ sudo ./dhcp_client
Sending DHCPDISCOVER...
Received DHCPOFFER from 192.168.1.1
Requesting 192.168.1.120...
Lease ACK received
IP: 192.168.1.120
Mask: 255.255.255.0
Gateway: 192.168.1.1
DNS: 1.1.1.1, 8.8.8.8
Lease: 86400 seconds
3.5 Data Formats / Schemas / Protocols
Protocols: Naming and Configuration Services (DNS, DHCP, mDNS), IP Addressing, Subnetting, and Routing (Including NAT).
3.6 Edge Cases
- Target unreachable or timing out
- Malformed or unexpected responses
- Multiple interfaces or subnets
3.7 Real World Outcome
$ sudo ./dhcp_client
Sending DHCPDISCOVER...
Received DHCPOFFER from 192.168.1.1
Requesting 192.168.1.120...
Lease ACK received
IP: 192.168.1.120
Mask: 255.255.255.0
Gateway: 192.168.1.1
DNS: 1.1.1.1, 8.8.8.8
Lease: 86400 seconds
3.7.1 How to Run (Copy/Paste)
- Build:
make(or create a virtual environment as needed) - Run:
./P06-dhcp-client - Config: update any constants in a config file or flags
- Working directory: project root
3.7.2 Golden Path Demo (Deterministic)
Run against a known local target and compare with the expected output.
3.7.3 If CLI: provide an exact terminal transcript
$ sudo ./dhcp_client
Sending DHCPDISCOVER...
Received DHCPOFFER from 192.168.1.1
Requesting 192.168.1.120...
Lease ACK received
IP: 192.168.1.120
Mask: 255.255.255.0
Gateway: 192.168.1.1
DNS: 1.1.1.1, 8.8.8.8
Lease: 86400 seconds
4. Solution Architecture
4.1 High-Level Design
CLI Input -> Core Engine -> Output/Logs
4.2 Key Components
| Component | Responsibility | Key Decisions |
|---|---|---|
| CLI Parser | Parse flags and inputs | Keep interface minimal |
| Core Engine | Protocol logic and state | Keep deterministic timing |
| Output/Logs | Present results and errors | Use consistent formatting |
4.4 Data Structures (No Full Code)
Request:
- target
- protocol fields
Response:
- status
- timing
State:
- retries
- cache entries
5. Implementation Guide
5.1 Development Environment Setup
- Ensure required tools (tcpdump, dig, ip) are installed.
- Use elevated privileges where raw sockets are required.
5.2 Project Structure
project/
README.md
docs/
src/
tests/
data/
5.3 The Core Question You’re Answering
“How does a device with no address join a network automatically?”
5.4 Concepts You Must Understand First
- DORA exchange
- What happens in discover, offer, request, ack?
- Book Reference: “TCP/IP Illustrated, Vol 1” - Ch. 21
- UDP broadcast mechanics
- Why are ports 67/68 used?
- Book Reference: “TCP/IP Illustrated, Vol 1” - Ch. 11
- DHCP options
- Which options are required for basic connectivity?
- Book Reference: RFC 2131
5.5 Questions to Guide Your Design
- State handling
- How do you track transaction IDs and retries?
- Lease timing
- When should renew and rebind happen?
5.6 Thinking Exercise
Lease expiry scenario
If a client cannot contact the DHCP server at renewal time, what should it do?
Questions to answer:
- What is the difference between renew and rebind?
- When does the client drop the lease?
5.7 The Interview Questions They’ll Ask
- “Why does DHCP use broadcast instead of unicast?”
- “What information does DHCP provide beyond IP address?”
- “What happens if two DHCP servers respond?”
- “How does a client renew its lease?”
- “How can you troubleshoot DHCP failures?”
5.8 Hints in Layers
Hint 1: Start with printing packets Log each DORA message to prove the state machine.
Hint 2: Use transaction IDs Match replies by transaction ID to avoid confusion.
Hint 3: Pseudocode outline
- broadcast DHCPDISCOVER
- wait for DHCPOFFER
- send DHCPREQUEST
- receive DHCPACK
- parse options and print
Hint 4: Verification Capture UDP ports 67/68 to confirm correct fields.
5.9 Books That Will Help
| Topic | Book | Chapter |
|---|---|---|
| DHCP | “TCP/IP Illustrated, Vol 1” | Ch. 21 |
| UDP | “TCP/IP Illustrated, Vol 1” | Ch. 11 |
| Configuration | “Computer Networks” | Ch. 7 |
5.10 Implementation Phases
- Establish core protocol I/O and a minimal success path.
- Add parsing, validation, and timeouts.
- Add logging, metrics, and polish for output.
5.11 Key Implementation Decisions
- Which interface and capture point provides visibility?
- What timeout and retry strategy balances speed and accuracy?
- How will results be validated against reference tools?
6. Testing Strategy
6.1 Test Categories
- Unit: parsing and validation logic
- Integration: protocol exchange with a real device
- System: full run with reference tools
6.2 Critical Test Cases
- Successful request/response path
- Timeout and retry behavior
- Invalid or unexpected input handling
6.3 Test Data
- Local gateway IP and a known reachable host
- A non-routable IP to trigger timeouts
7. Common Pitfalls & Debugging
7.1 Frequent Mistakes
Problem 1: “No offer received”
- Why: Wrong interface or blocked broadcast.
- Fix: Bind to correct interface and verify broadcast is allowed.
- Quick test: Capture DHCPOFFER with
tcpdump.
Problem 2: “Lease obtained but no internet”
- Why: Missing gateway or DNS option.
- Fix: Validate DHCP options and print them clearly.
- Quick test: Compare with system DHCP client output.
7.2 Debugging Strategies
- Capture traffic with tcpdump or Wireshark.
- Compare against a known-good tool.
- Log timestamps and retry logic.
7.3 Performance Traps
- Excessive retries causing long runtimes.
- Inefficient parsing under high packet rates.
8. Extensions & Challenges
8.1 Beginner Extensions
- Add basic configuration flags for interface and timeout.
- Improve output formatting and sorting.
8.2 Intermediate Extensions
- Add caching or state persistence.
- Add CSV or JSON output export.
8.3 Advanced Extensions
- Add concurrency with careful rate limiting.
- Add visualization or integration with a dashboard.
9. Real-World Connections
9.1 Industry Applications
- Network diagnostics and troubleshooting
- Security monitoring and policy enforcement
9.2 Related Open Source Projects
- tcpdump / Wireshark
- nmap / dnsmasq / unbound (as applicable)
9.3 Interview Relevance
- Explaining protocol behavior
- Diagnosing failures by layer
10. Resources
10.1 Essential Reading
| Topic | Book | Chapter |
|---|---|---|
| DHCP | “TCP/IP Illustrated, Vol 1” | Ch. 21 |
| UDP | “TCP/IP Illustrated, Vol 1” | Ch. 11 |
| Configuration | “Computer Networks” | Ch. 7 |
10.2 Video Resources
- Wireshark or tcpdump walkthroughs (search for recent tutorials)
- Vendor or RFC explainers for the relevant protocol
10.3 Tools & Documentation
- RFCs for the protocols used in this project
man tcpdump,man ip,man ss
10.4 Related Projects in This Series
- Project 1: Network Device Scanner (ARP Discovery Tool)
- Project 3: Build Your Own traceroute Utility
- Project 5: DNS Resolver (Client-Side)
- Project 7: Simple DNS Server (Authoritative)
- Project 8: DHCP Server
- Project 10: DNS Sinkhole (Pi-hole Style)
- Project 13: Simple Packet Filter Firewall
- Project 14: Software Router with NAT
- Project 16: mDNS/Bonjour Service Discovery
- Project 18: Network Topology Mapper
- Project 20: Complete Home Network Stack (Capstone)