couchdb
+
+
+
+
oauth
rest
grpc
nuxt
aws
+
scipy
elasticsearch
chef
+
composer
+
json
jax
suse
+
+
grafana
sinatra
+
fauna
+
+
+
+
prometheus
?
+
rollup
haiku
+
bitbucket
โˆช
gh
+
k8s
rb
java
+
prettier
+
::
+
+
+
npm
websocket
+
+
+
+
firebase
+
+
+
symfony
+
riot
+
+
groovy
r
babel
//
xml
+
+
+
jax
+
clickhouse
rocket
angular
+
+
โŠ‚
+
+
suse
cypress
+
py
+
css
+
Back to Blog
๐ŸŒ Configuring DHCP Client: Simple Guide
Alpine Linux Networking DHCP

๐ŸŒ Configuring DHCP Client: Simple Guide

Published Jun 4, 2025

Easy tutorial for beginners to configure DHCP client on Alpine Linux. Perfect for network setup with step-by-step instructions and clear examples.

8 min read
0 views
Table of Contents

๐ŸŒ Configuring DHCP Client: Simple Guide

Letโ€™s configure DHCP client on your Alpine Linux system! ๐Ÿ“ก This guide uses easy steps and simple words. Weโ€™ll get your network connected automatically! ๐Ÿ˜Š

๐Ÿค” What is DHCP Client?

DHCP client is like having a helpful assistant that automatically gets you the right network settings!

Think of DHCP client like:

  • ๐Ÿ“ A hotel concierge who gives you room keys, WiFi passwords, and local information when you check in
  • ๐Ÿ”ง A helpful friend who sets up your phone with all the right network settings
  • ๐Ÿ’ก An automatic system that configures your carโ€™s GPS with the current location and routes

๐ŸŽฏ What You Need

Before we start, you need:

  • โœ… Alpine Linux system running
  • โœ… Root access or sudo permissions
  • โœ… Network interface (ethernet or wireless)
  • โœ… Access to a network with DHCP server (router/modem)

๐Ÿ“‹ Step 1: Check Network Interface Status

Identify Available Network Interfaces

First, letโ€™s see what network interfaces we have! ๐Ÿ˜Š

What weโ€™re doing: Discovering and examining your network interfaces to understand what weโ€™re working with before configuring DHCP.

# Install network tools
apk update
apk add iproute2 dhcpcd ifupdown-ng net-tools

# List all network interfaces
ip link show

# Check interface details
ip addr show

# See interface statistics
cat /proc/net/dev

# Check interface status with traditional tools
ifconfig -a

# Check which interfaces are up
ip link show up

# Check current IP configuration
hostname -i 2>/dev/null || echo "No IP assigned"

# Check current routing table
ip route show

# Check DNS configuration
cat /etc/resolv.conf

# Check network manager status
rc-service networking status

What this does: ๐Ÿ“– Shows you all available network interfaces and their current configuration status.

Example output:

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
    link/ether 08:00:27:12:34:56 brd ff:ff:ff:ff:ff:ff
3: wlan0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DEFAULT group default qlen 1000
    link/ether 02:11:22:33:44:55 brd ff:ff:ff:ff:ff:ff

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.1.100  netmask 255.255.255.0  broadcast 192.168.1.255
        ether 08:00:27:12:34:56  txqueuelen 1000  (Ethernet)

What this means: You can see your network interfaces and their current state! โœ…

๐Ÿ’ก Important Tips

Tip: Make note of your interface names (like eth0, wlan0) as youโ€™ll need them! ๐Ÿ’ก

Warning: Changing network settings can disconnect you from SSH sessions! โš ๏ธ

๐Ÿ› ๏ธ Step 2: Configure DHCP Client with dhcpcd

Set Up dhcpcd Service

Now letโ€™s configure the DHCP client daemon! ๐Ÿ˜Š

What weโ€™re doing: Installing and configuring dhcpcd, which is a modern and reliable DHCP client that can automatically configure your network interfaces.

# Install dhcpcd
apk add dhcpcd

# Create dhcpcd configuration
cat > /etc/dhcpcd.conf << 'EOF'
# DHCP Client Configuration

# Basic configuration
hostname

# Request specific information from DHCP server
option domain_name_servers, domain_name, domain_search, host_name
option classless_static_routes
option ntp_servers

# Timeout settings
timeout 30
reboot 5

# Interface configuration
allowinterfaces eth0 wlan0

# Security options
require dhcp_server_identifier

# Use the hardware address of the interface for the Client ID
clientid

# Persist interface configuration when dhcpcd exits
persistent

# Rapid commit support (faster DHCP)
option rapid_commit

# A list of options to request from the DHCP server
option subnet_mask, routers, domain_name_servers, domain_name
option broadcast_address, ntp_servers, netbios_name_servers
option netbios_scope, interface_mtu, rfc3442_classless_static_routes

# Vendor class identifier
#vendorclassid "Alpine Linux"

# Fallback to static IP if DHCP fails
#profile static_eth0
#static ip_address=192.168.1.100/24
#static routers=192.168.1.1
#static domain_name_servers=8.8.8.8 1.1.1.1

# Interface-specific configurations
interface eth0
    # Enable IPv6 DHCP
    ipv6rs
    ia_na 1
    
interface wlan0
    # Wireless-specific settings
    env ifwireless=1
    ipv6rs
EOF

# Backup existing network configuration
cp /etc/network/interfaces /etc/network/interfaces.backup 2>/dev/null || echo "No existing interfaces file"

# Create basic network interfaces configuration
cat > /etc/network/interfaces << 'EOF'
# Network Interface Configuration

auto lo
iface lo inet loopback

# Ethernet interface managed by dhcpcd
auto eth0
iface eth0 inet dhcp

# Wireless interface managed by dhcpcd  
#auto wlan0
#iface wlan0 inet dhcp
EOF

# Enable and start dhcpcd service
rc-update add dhcpcd default
rc-service dhcpcd start

# Check dhcpcd status
rc-service dhcpcd status

# View dhcpcd logs
tail -20 /var/log/messages | grep dhcpcd

DHCP configuration features:

  • Automatic IP address assignment
  • DNS server configuration
  • Default gateway setup
  • NTP server discovery
  • IPv6 support
  • Fallback options for reliability

What this means: Your system will automatically get network configuration from DHCP! ๐ŸŽ‰

๐ŸŽฎ Step 3: Test DHCP Configuration

Verify Network Connectivity

Letโ€™s test if DHCP is working correctly! ๐ŸŽฏ

What weโ€™re doing: Testing the DHCP client configuration to ensure itโ€™s properly obtaining network settings and establishing connectivity.

# Release current DHCP lease
dhcpcd -k eth0 2>/dev/null || echo "No active lease to release"

# Request new DHCP lease
dhcpcd -T eth0

# Check if IP was assigned
ip addr show eth0

# Test connectivity
ping -c 3 8.8.8.8

# Test DNS resolution
nslookup google.com

# Check routing table
ip route show

# Check DHCP lease information
cat /var/lib/dhcpcd/dhcpcd.leases 2>/dev/null || echo "No lease file found"

# Test network services
curl -s http://httpbin.org/ip | head -5 2>/dev/null || echo "HTTP test failed"

# Check DNS servers
cat /etc/resolv.conf

# Monitor DHCP client activity
dhcpcd -T -d eth0 &
dhcp_pid=$!
sleep 10
kill $dhcp_pid 2>/dev/null

# Verify network configuration
echo "=== Network Configuration Summary ==="
echo "Interface: $(ip addr show eth0 | grep 'inet ' | awk '{print $2}')"
echo "Gateway: $(ip route | grep default | awk '{print $3}')"
echo "DNS: $(cat /etc/resolv.conf | grep nameserver | awk '{print $2}' | tr '\n' ' ')"
echo "MTU: $(ip link show eth0 | grep mtu | awk '{print $5}')"

You should see:

PING 8.8.8.8 (8.8.8.8): 56 data bytes
64 bytes from 8.8.8.8: seq=0 ttl=116 time=12.345 ms
64 bytes from 8.8.8.8: seq=1 ttl=116 time=11.234 ms
64 bytes from 8.8.8.8: seq=2 ttl=116 time=13.456 ms

Server:    192.168.1.1
Address:   192.168.1.1:53

Name:      google.com
Address:   142.250.191.110

=== Network Configuration Summary ===
Interface: 192.168.1.100/24
Gateway: 192.168.1.1
DNS: 192.168.1.1 8.8.8.8
MTU: 1500

Awesome work! DHCP client is working perfectly! ๐ŸŒŸ

๐Ÿ“Š Step 4: Advanced DHCP Configuration

Customize DHCP Behavior

Now letโ€™s add advanced DHCP features! ๐Ÿ˜Š

What weโ€™re doing: Implementing advanced DHCP client features like custom options, multiple interface support, and failover configurations.

# Create advanced dhcpcd configuration
cat > /etc/dhcpcd.conf << 'EOF'
# Advanced DHCP Client Configuration

# General settings
hostname
clientid
persistent
option rapid_commit

# Request comprehensive DHCP options
option domain_name_servers, domain_name, domain_search
option classless_static_routes, ms_classless_static_routes
option ntp_servers, time_servers
option netbios_name_servers, netbios_scope
option interface_mtu, broadcast_address
option dhcp_lease_time, dhcp_renewal_time, dhcp_rebinding_time

# Timeout and retry settings
timeout 60
reboot 10

# Interface priority (higher number = higher priority)
metric 100

# Enable IPv6
ipv6rs

# DHCP-specific options
vendorclassid "Alpine Linux DHCP Client"

# Security enhancements
require dhcp_server_identifier
nohook resolv.conf  # Manage DNS manually for security

# Multiple interface support
allowinterfaces eth* wlan*

# Interface-specific configurations
interface eth0
    metric 100
    
    # Request specific options for ethernet
    option routers, static_routes
    
    # Ethernet-specific hooks
    env force_hostname=1

interface wlan0
    metric 200  # Lower priority than ethernet
    
    # Wireless-specific settings
    env ifwireless=1
    
    # Different timeout for wireless
    timeout 90

# Fallback static configuration
profile static_fallback
static ip_address=192.168.1.200/24
static routers=192.168.1.1
static domain_name_servers=8.8.8.8 1.1.1.1

# Define when to use fallback
interface eth0
    fallback static_fallback
EOF

# Create custom DHCP hooks
mkdir -p /lib/dhcpcd/dhcpcd-hooks

# Create DNS management hook
cat > /lib/dhcpcd/dhcpcd-hooks/20-resolv.conf << 'EOF'
#!/bin/sh
# Custom DNS management hook

resolv_conf_dir="/etc"
resolv_conf="$resolv_conf_dir/resolv.conf"

make_resolv_conf() {
    # Create secure resolv.conf
    {
        echo "# Generated by dhcpcd"
        echo "# $(date)"
        
        if [ -n "$new_domain_name" ]; then
            echo "domain $new_domain_name"
        fi
        
        if [ -n "$new_domain_search" ]; then
            echo "search $new_domain_search"
        elif [ -n "$new_domain_name" ]; then
            echo "search $new_domain_name"
        fi
        
        # Add DHCP-provided DNS servers
        for dns in $new_domain_name_servers; do
            echo "nameserver $dns"
        done
        
        # Add fallback DNS servers
        echo "nameserver 8.8.8.8"
        echo "nameserver 1.1.1.1"
        
    } > "$resolv_conf.tmp"
    
    # Atomic update
    mv "$resolv_conf.tmp" "$resolv_conf"
    chmod 644 "$resolv_conf"
}

case "$reason" in
    BOUND|RENEW|REBIND|REBOOT)
        make_resolv_conf
        ;;
    EXPIRE|FAIL|RELEASE|STOP)
        # Keep last known good configuration
        ;;
esac
EOF

chmod +x /lib/dhcpcd/dhcpcd-hooks/20-resolv.conf

# Create logging hook
cat > /lib/dhcpcd/dhcpcd-hooks/30-logger << 'EOF'
#!/bin/sh
# DHCP Event Logger

log_file="/var/log/dhcp-events.log"

log_event() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - Interface: $interface, Reason: $reason, IP: $new_ip_address" >> "$log_file"
}

case "$reason" in
    BOUND)
        log_event
        logger -t dhcpcd "DHCP lease acquired for $interface: $new_ip_address"
        ;;
    RENEW)
        log_event
        logger -t dhcpcd "DHCP lease renewed for $interface: $new_ip_address"
        ;;
    EXPIRE|FAIL)
        log_event
        logger -t dhcpcd "DHCP lease expired/failed for $interface"
        ;;
    RELEASE)
        log_event
        logger -t dhcpcd "DHCP lease released for $interface"
        ;;
esac
EOF

chmod +x /lib/dhcpcd/dhcpcd-hooks/30-logger

# Create network monitoring script
cat > /usr/local/bin/dhcp-monitor.sh << 'EOF'
#!/bin/bash
# DHCP Client Monitor

while true; do
    clear
    echo "๐ŸŒ DHCP CLIENT MONITOR - $(date)"
    echo "=============================="
    echo
    
    echo "๐Ÿ“ก Active Network Interfaces:"
    ip -brief addr show | grep -E "(eth|wlan)" | awk '{printf "  %-8s %-15s %s\n", $1, $2, $3}'
    echo
    
    echo "๐Ÿ”— DHCP Lease Information:"
    if [ -f /var/lib/dhcpcd/dhcpcd.leases ]; then
        grep -E "(interface|fixed-address|routers|domain-name-servers)" /var/lib/dhcpcd/dhcpcd.leases | tail -8 | \
        while read line; do
            echo "  $line"
        done
    else
        echo "  No DHCP lease file found"
    fi
    echo
    
    echo "๐ŸŒ Connectivity Status:"
    # Test connectivity
    if ping -c 1 -W 2 8.8.8.8 >/dev/null 2>&1; then
        echo "  Internet: โœ… Connected"
    else
        echo "  Internet: โŒ No connection"
    fi
    
    if ping -c 1 -W 2 $(ip route | grep default | awk '{print $3}' | head -1) >/dev/null 2>&1; then
        echo "  Gateway: โœ… Reachable"
    else
        echo "  Gateway: โŒ Unreachable"
    fi
    
    if nslookup google.com >/dev/null 2>&1; then
        echo "  DNS: โœ… Working"
    else
        echo "  DNS: โŒ Failed"
    fi
    echo
    
    echo "๐Ÿ“Š DHCP Process Status:"
    if pgrep dhcpcd >/dev/null; then
        echo "  dhcpcd: โœ… Running (PID: $(pgrep dhcpcd))"
    else
        echo "  dhcpcd: โŒ Not running"
    fi
    echo
    
    echo "๐Ÿ“ˆ Recent DHCP Events:"
    if [ -f /var/log/dhcp-events.log ]; then
        tail -3 /var/log/dhcp-events.log | sed 's/^/  /'
    else
        echo "  No DHCP events logged"
    fi
    echo
    
    echo "Press Ctrl+C to exit, refreshing in 5 seconds..."
    sleep 5
done
EOF

chmod +x /usr/local/bin/dhcp-monitor.sh

# Restart dhcpcd with new configuration
rc-service dhcpcd restart

# Wait for DHCP to complete
sleep 10

# Verify new configuration
dhcpcd -T eth0

Advanced features configured:

  • Multiple interface support with priorities
  • Custom DNS management for security
  • Comprehensive option requests
  • Event logging and monitoring
  • Fallback static configuration

What this creates:

DHCP client:     Advanced configuration with multiple interfaces
DNS management:  Secure with fallback servers
Event logging:   Complete DHCP activity tracking
Monitoring:      Real-time status dashboard
Failover:        Static IP fallback if DHCP fails

Great job! Advanced DHCP client configuration is complete! ๐ŸŒŸ

๐Ÿ“Š Quick Summary Table

What to DoCommandResult
๐Ÿ”ง Install DHCP clientapk add dhcpcdโœ… DHCP software
๐Ÿ› ๏ธ Configure clientdhcpcd.confโœ… Auto network config
๐ŸŽฏ Test connectivityping 8.8.8.8โœ… Internet access
๐Ÿš€ Monitor statusdhcp-monitor.shโœ… Real-time monitoring

๐ŸŒ Step 5: Troubleshooting and Maintenance

Debug DHCP Issues

Letโ€™s set up comprehensive DHCP troubleshooting! ๐ŸŒ

What weโ€™re doing: Creating debugging tools and maintenance procedures to diagnose and fix DHCP client issues.

# Create DHCP troubleshooting script
cat > /usr/local/bin/dhcp-troubleshoot.sh << 'EOF'
#!/bin/bash
# DHCP Client Troubleshooting Tool

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log_file="/var/log/dhcp-troubleshoot.log"

print_status() {
    local status="$1"
    local message="$2"
    
    case "$status" in
        "OK")
            echo -e "${GREEN}โœ… $message${NC}"
            ;;
        "WARN")
            echo -e "${YELLOW}โš ๏ธ  $message${NC}"
            ;;
        "ERROR")
            echo -e "${RED}โŒ $message${NC}"
            ;;
    esac
}

check_interface() {
    local interface="$1"
    
    echo "๐Ÿ” Checking interface: $interface"
    echo "================================"
    
    # Check if interface exists
    if ip link show "$interface" >/dev/null 2>&1; then
        print_status "OK" "Interface $interface exists"
    else
        print_status "ERROR" "Interface $interface not found"
        return 1
    fi
    
    # Check if interface is up
    if ip link show "$interface" | grep -q "state UP"; then
        print_status "OK" "Interface $interface is UP"
    else
        print_status "WARN" "Interface $interface is DOWN"
        echo "  Attempting to bring up interface..."
        ip link set "$interface" up
        sleep 2
        if ip link show "$interface" | grep -q "state UP"; then
            print_status "OK" "Interface $interface brought up successfully"
        else
            print_status "ERROR" "Failed to bring up interface $interface"
        fi
    fi
    
    # Check for carrier (physical connection)
    if [ -f "/sys/class/net/$interface/carrier" ]; then
        if [ "$(cat /sys/class/net/$interface/carrier 2>/dev/null)" = "1" ]; then
            print_status "OK" "Physical connection detected on $interface"
        else
            print_status "WARN" "No physical connection on $interface"
        fi
    fi
    
    # Check IP assignment
    if ip addr show "$interface" | grep -q "inet "; then
        local ip=$(ip addr show "$interface" | grep "inet " | awk '{print $2}')
        print_status "OK" "IP assigned: $ip"
    else
        print_status "WARN" "No IP address assigned to $interface"
    fi
    
    echo
}

check_dhcp_service() {
    echo "๐Ÿ”ง Checking DHCP Service"
    echo "========================"
    
    # Check if dhcpcd is running
    if pgrep dhcpcd >/dev/null; then
        print_status "OK" "dhcpcd service is running"
        echo "  PID: $(pgrep dhcpcd)"
    else
        print_status "ERROR" "dhcpcd service is not running"
        echo "  Attempting to start dhcpcd..."
        rc-service dhcpcd start
        sleep 3
        if pgrep dhcpcd >/dev/null; then
            print_status "OK" "dhcpcd started successfully"
        else
            print_status "ERROR" "Failed to start dhcpcd"
        fi
    fi
    
    # Check dhcpcd configuration
    if [ -f /etc/dhcpcd.conf ]; then
        print_status "OK" "dhcpcd configuration file exists"
    else
        print_status "WARN" "dhcpcd configuration file missing"
    fi
    
    # Check for DHCP lease
    if [ -f /var/lib/dhcpcd/dhcpcd.leases ]; then
        print_status "OK" "DHCP lease file exists"
        local lease_count=$(grep -c "lease" /var/lib/dhcpcd/dhcpcd.leases)
        echo "  Leases found: $lease_count"
    else
        print_status "WARN" "No DHCP lease file found"
    fi
    
    echo
}

check_connectivity() {
    echo "๐ŸŒ Checking Connectivity"
    echo "======================="
    
    # Check default route
    if ip route | grep -q "default"; then
        local gateway=$(ip route | grep default | awk '{print $3}' | head -1)
        print_status "OK" "Default gateway: $gateway"
        
        # Test gateway connectivity
        if ping -c 1 -W 3 "$gateway" >/dev/null 2>&1; then
            print_status "OK" "Gateway is reachable"
        else
            print_status "ERROR" "Gateway is unreachable"
        fi
    else
        print_status "ERROR" "No default route found"
    fi
    
    # Check DNS configuration
    if [ -f /etc/resolv.conf ]; then
        local dns_servers=$(grep nameserver /etc/resolv.conf | wc -l)
        if [ "$dns_servers" -gt 0 ]; then
            print_status "OK" "DNS servers configured ($dns_servers found)"
        else
            print_status "WARN" "No DNS servers configured"
        fi
    else
        print_status "ERROR" "resolv.conf file missing"
    fi
    
    # Test internet connectivity
    if ping -c 1 -W 5 8.8.8.8 >/dev/null 2>&1; then
        print_status "OK" "Internet connectivity working"
    else
        print_status "ERROR" "No internet connectivity"
    fi
    
    # Test DNS resolution
    if nslookup google.com >/dev/null 2>&1; then
        print_status "OK" "DNS resolution working"
    else
        print_status "ERROR" "DNS resolution failed"
    fi
    
    echo
}

run_dhcp_debug() {
    local interface="$1"
    
    echo "๐Ÿ› Running DHCP Debug for $interface"
    echo "==================================="
    
    # Kill existing dhcpcd for this interface
    dhcpcd -k "$interface" 2>/dev/null
    sleep 2
    
    # Run dhcpcd in debug mode
    echo "Starting DHCP debug session (10 seconds)..."
    timeout 10 dhcpcd -d -T "$interface" 2>&1 | tee -a "$log_file"
    
    echo "Debug session completed. Check $log_file for details."
    echo
}

fix_common_issues() {
    echo "๐Ÿ”ง Applying Common Fixes"
    echo "======================="
    
    # Restart network service
    print_status "OK" "Restarting network service..."
    rc-service networking restart
    sleep 3
    
    # Restart dhcpcd
    print_status "OK" "Restarting dhcpcd service..."
    rc-service dhcpcd restart
    sleep 5
    
    # Clear DNS cache
    print_status "OK" "Clearing DNS cache..."
    echo "nameserver 8.8.8.8" > /etc/resolv.conf.tmp
    echo "nameserver 1.1.1.1" >> /etc/resolv.conf.tmp
    mv /etc/resolv.conf.tmp /etc/resolv.conf
    
    # Renew DHCP lease
    for interface in $(ip -o link show | awk -F': ' '{print $2}' | grep -E "^(eth|wlan)"); do
        print_status "OK" "Renewing DHCP lease for $interface..."
        dhcpcd -n "$interface" 2>/dev/null &
    done
    
    sleep 10
    echo "Common fixes applied. Please test connectivity."
    echo
}

# Main troubleshooting routine
main() {
    echo "๐Ÿšจ DHCP CLIENT TROUBLESHOOTING TOOL"
    echo "===================================="
    echo "$(date)"
    echo
    
    # Log start of troubleshooting
    echo "$(date '+%Y-%m-%d %H:%M:%S') - Starting DHCP troubleshooting" >> "$log_file"
    
    # Get primary interface
    primary_interface=$(ip route | grep default | awk '{print $5}' | head -1)
    if [ -z "$primary_interface" ]; then
        primary_interface=$(ip -o link show | awk -F': ' '{print $2}' | grep -E "^(eth|wlan)" | head -1)
    fi
    
    echo "Primary interface detected: ${primary_interface:-"None found"}"
    echo
    
    # Run checks
    check_dhcp_service
    
    if [ -n "$primary_interface" ]; then
        check_interface "$primary_interface"
    fi
    
    check_connectivity
    
    # Offer to run debug or fixes
    echo "Would you like to:"
    echo "1) Run DHCP debug session"
    echo "2) Apply common fixes"
    echo "3) Exit"
    echo
    read -p "Enter choice (1-3): " choice
    
    case "$choice" in
        1)
            if [ -n "$primary_interface" ]; then
                run_dhcp_debug "$primary_interface"
            else
                echo "No interface available for debugging"
            fi
            ;;
        2)
            fix_common_issues
            ;;
        3)
            echo "Exiting troubleshooter"
            ;;
        *)
            echo "Invalid choice"
            ;;
    esac
    
    echo "$(date '+%Y-%m-%d %H:%M:%S') - DHCP troubleshooting completed" >> "$log_file"
}

# Run if called directly
if [ "${BASH_SOURCE[0]}" = "${0}" ]; then
    main "$@"
fi
EOF

chmod +x /usr/local/bin/dhcp-troubleshoot.sh

# Create DHCP lease renewal script
cat > /usr/local/bin/dhcp-renew.sh << 'EOF'
#!/bin/bash
# DHCP Lease Renewal Script

renew_interface() {
    local interface="$1"
    
    echo "๐Ÿ”„ Renewing DHCP lease for $interface..."
    
    # Release current lease
    dhcpcd -k "$interface" 2>/dev/null
    sleep 2
    
    # Request new lease
    dhcpcd -n "$interface"
    sleep 5
    
    # Check if successful
    if ip addr show "$interface" | grep -q "inet "; then
        echo "โœ… DHCP renewal successful for $interface"
        ip addr show "$interface" | grep "inet " | awk '{print "   New IP:", $2}'
    else
        echo "โŒ DHCP renewal failed for $interface"
    fi
}

# Renew all active interfaces
for interface in $(ip -o link show up | awk -F': ' '{print $2}' | grep -E "^(eth|wlan)"); do
    renew_interface "$interface"
    echo
done

# Test connectivity after renewal
echo "๐ŸŒ Testing connectivity..."
if ping -c 3 8.8.8.8 >/dev/null 2>&1; then
    echo "โœ… Internet connectivity restored"
else
    echo "โŒ Internet connectivity still not working"
fi
EOF

chmod +x /usr/local/bin/dhcp-renew.sh

# Set up DHCP monitoring cron job
echo "*/30 * * * * /usr/local/bin/dhcp-monitor.sh status >> /var/log/dhcp-monitor.log 2>&1" >> /etc/crontabs/root

echo "DHCP troubleshooting tools installed!"
echo "Run '/usr/local/bin/dhcp-troubleshoot.sh' to diagnose issues"

What this does: Provides comprehensive DHCP troubleshooting and maintenance tools! ๐Ÿ“š

Example: DHCP Performance Testing ๐ŸŸก

What weโ€™re doing: Testing DHCP client performance and reliability under various conditions.

# Create DHCP performance test script
cat > /usr/local/bin/dhcp-performance-test.sh << 'EOF'
#!/bin/bash
# DHCP Performance Test Suite

test_results="/var/log/dhcp-performance-$(date +%Y%m%d-%H%M%S).log"

echo "๐Ÿš€ DHCP PERFORMANCE TEST SUITE - $(date)" | tee "$test_results"
echo "=========================================" | tee -a "$test_results"
echo | tee -a "$test_results"

test_dhcp_timing() {
    local interface="$1"
    local iterations="$2"
    
    echo "โฑ๏ธ  DHCP Timing Test for $interface" | tee -a "$test_results"
    echo "Iterations: $iterations" | tee -a "$test_results"
    echo | tee -a "$test_results"
    
    local total_time=0
    local successful=0
    
    for i in $(seq 1 $iterations); do
        echo "Test $i/$iterations..." | tee -a "$test_results"
        
        # Release lease
        dhcpcd -k "$interface" >/dev/null 2>&1
        sleep 1
        
        # Time the DHCP request
        start_time=$(date +%s.%N)
        dhcpcd -T "$interface" >/dev/null 2>&1
        
        # Check if IP was assigned
        if ip addr show "$interface" | grep -q "inet "; then
            end_time=$(date +%s.%N)
            duration=$(echo "$end_time - $start_time" | bc)
            total_time=$(echo "$total_time + $duration" | bc)
            successful=$((successful + 1))
            echo "  Success in ${duration}s" | tee -a "$test_results"
        else
            echo "  Failed" | tee -a "$test_results"
        fi
        
        sleep 2
    done
    
    if [ $successful -gt 0 ]; then
        avg_time=$(echo "scale=2; $total_time / $successful" | bc)
        success_rate=$(echo "scale=1; $successful * 100 / $iterations" | bc)
        echo | tee -a "$test_results"
        echo "Results:" | tee -a "$test_results"
        echo "  Success Rate: ${success_rate}%" | tee -a "$test_results"
        echo "  Average Time: ${avg_time}s" | tee -a "$test_results"
        echo "  Successful: $successful/$iterations" | tee -a "$test_results"
    else
        echo "  All tests failed!" | tee -a "$test_results"
    fi
    
    echo | tee -a "$test_results"
}

test_dhcp_reliability() {
    local interface="$1"
    
    echo "๐Ÿ”„ DHCP Reliability Test for $interface" | tee -a "$test_results"
    echo "Testing lease renewal and persistence..." | tee -a "$test_results"
    echo | tee -a "$test_results"
    
    # Get initial IP
    initial_ip=$(ip addr show "$interface" | grep "inet " | awk '{print $2}' | cut -d'/' -f1)
    echo "Initial IP: $initial_ip" | tee -a "$test_results"
    
    # Force renewal multiple times
    for i in {1..5}; do
        echo "Renewal test $i/5..." | tee -a "$test_results"
        dhcpcd -n "$interface" >/dev/null 2>&1
        sleep 3
        
        current_ip=$(ip addr show "$interface" | grep "inet " | awk '{print $2}' | cut -d'/' -f1)
        if [ "$current_ip" = "$initial_ip" ]; then
            echo "  IP maintained: $current_ip" | tee -a "$test_results"
        else
            echo "  IP changed: $initial_ip โ†’ $current_ip" | tee -a "$test_results"
        fi
    done
    
    echo | tee -a "$test_results"
}

test_dhcp_failover() {
    local interface="$1"
    
    echo "๐Ÿ›ก๏ธ  DHCP Failover Test for $interface" | tee -a "$test_results"
    echo "Testing behavior when DHCP server is unavailable..." | tee -a "$test_results"
    echo | tee -a "$test_results"
    
    # Simulate DHCP server unavailable by blocking DHCP traffic
    echo "Blocking DHCP traffic..." | tee -a "$test_results"
    iptables -I OUTPUT -p udp --dport 67 -j DROP 2>/dev/null
    iptables -I OUTPUT -p udp --dport 68 -j DROP 2>/dev/null
    
    # Release and try to renew
    dhcpcd -k "$interface" >/dev/null 2>&1
    sleep 2
    
    start_time=$(date +%s)
    timeout 30 dhcpcd -T "$interface" >/dev/null 2>&1
    end_time=$(date +%s)
    
    duration=$((end_time - start_time))
    echo "DHCP timeout after ${duration}s" | tee -a "$test_results"
    
    # Remove firewall rules
    iptables -D OUTPUT -p udp --dport 67 -j DROP 2>/dev/null
    iptables -D OUTPUT -p udp --dport 68 -j DROP 2>/dev/null
    
    # Restore DHCP
    echo "Restoring DHCP..." | tee -a "$test_results"
    dhcpcd -n "$interface" >/dev/null 2>&1
    sleep 5
    
    if ip addr show "$interface" | grep -q "inet "; then
        restored_ip=$(ip addr show "$interface" | grep "inet " | awk '{print $2}' | cut -d'/' -f1)
        echo "DHCP restored: $restored_ip" | tee -a "$test_results"
    else
        echo "DHCP restoration failed" | tee -a "$test_results"
    fi
    
    echo | tee -a "$test_results"
}

# Main test execution
main_interface=$(ip route | grep default | awk '{print $5}' | head -1)

if [ -z "$main_interface" ]; then
    echo "No active network interface found for testing" | tee -a "$test_results"
    exit 1
fi

echo "Testing interface: $main_interface" | tee -a "$test_results"
echo | tee -a "$test_results"

# Run performance tests
test_dhcp_timing "$main_interface" 5
test_dhcp_reliability "$main_interface"
test_dhcp_failover "$main_interface"

echo "โœ… DHCP performance testing completed" | tee -a "$test_results"
echo "Results saved to: $test_results" | tee -a "$test_results"
EOF

chmod +x /usr/local/bin/dhcp-performance-test.sh

echo "DHCP performance testing tools ready!"
echo "Run '/usr/local/bin/dhcp-performance-test.sh' to test performance"

What this does: Provides comprehensive DHCP performance and reliability testing! ๐ŸŒŸ

๐Ÿšจ Fix Common Problems

Problem 1: DHCP client not getting IP address โŒ

What happened: Interface comes up but no IP is assigned. How to fix it: Check service and network connectivity!

# Check if dhcpcd is running
rc-service dhcpcd status

# Restart dhcpcd service
rc-service dhcpcd restart

# Check interface status
ip link show eth0

# Bring up interface manually
ip link set eth0 up

# Request DHCP lease manually
dhcpcd -d eth0

Problem 2: DNS not working after DHCP โŒ

What happened: IP assigned but DNS resolution fails. How to fix it: Check DNS configuration and resolv.conf!

# Check DNS servers
cat /etc/resolv.conf

# Manually set DNS servers
echo "nameserver 8.8.8.8" > /etc/resolv.conf
echo "nameserver 1.1.1.1" >> /etc/resolv.conf

# Test DNS resolution
nslookup google.com

# Restart dhcpcd to regenerate resolv.conf
rc-service dhcpcd restart

Problem 3: DHCP lease expires frequently โŒ

What happened: Connection drops due to short lease times. How to fix it: Configure lease renewal and longer timeouts!

# Check lease information
cat /var/lib/dhcpcd/dhcpcd.leases

# Configure longer timeout in dhcpcd.conf
echo "timeout 300" >> /etc/dhcpcd.conf

# Set lease renewal timing
echo "option dhcp_lease_time" >> /etc/dhcpcd.conf

# Restart dhcpcd
rc-service dhcpcd restart

Donโ€™t worry! These problems happen to everyone. Youโ€™re doing great! ๐Ÿ’ช

๐Ÿ’ก Simple Tips

  1. Use wired connections when possible ๐Ÿ“… - More reliable than wireless for DHCP
  2. Monitor lease expiration ๐ŸŒฑ - Keep track of when leases need renewal
  3. Test after configuration changes ๐Ÿค - Verify connectivity after modifications
  4. Keep static IP as backup ๐Ÿ’ช - Have fallback configuration ready

โœ… Check Everything Works

Letโ€™s make sure everything is working:

# Check DHCP service status
rc-service dhcpcd status

# Verify IP assignment
ip addr show | grep inet

# Test internet connectivity
ping -c 3 8.8.8.8

# Test DNS resolution
nslookup google.com

# Check DHCP lease
cat /var/lib/dhcpcd/dhcpcd.leases | tail -10

# Monitor DHCP activity
/usr/local/bin/dhcp-monitor.sh &
sleep 10
pkill -f dhcp-monitor

# Run troubleshooter
/usr/local/bin/dhcp-troubleshoot.sh

# You should see this
echo "DHCP client is configured and working perfectly! โœ…"

Good output:

* status: started

2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    inet 192.168.1.100/24 brd 192.168.1.255 scope global dynamic eth0

PING 8.8.8.8 (8.8.8.8): 56 data bytes
64 bytes from 8.8.8.8: seq=0 ttl=116 time=12.345 ms

Server:    192.168.1.1
Address:   192.168.1.1:53

lease {
  interface "eth0";
  fixed-address 192.168.1.100;
  routers 192.168.1.1;
  domain-name-servers 192.168.1.1, 8.8.8.8;
}

โœ… dhcpcd service is running
โœ… Interface eth0 is UP  
โœ… IP assigned: 192.168.1.100/24
โœ… Gateway is reachable
โœ… Internet connectivity working
โœ… DNS resolution working

โœ… Success! DHCP client is fully operational and network connectivity is working.

๐Ÿ† What You Learned

Great job! Now you can:

  • โœ… Configure DHCP client for automatic network setup
  • โœ… Customize DHCP behavior with advanced options
  • โœ… Set up multiple interface support and priorities
  • โœ… Implement DHCP monitoring and troubleshooting
  • โœ… Handle failover scenarios and reliability testing

๐ŸŽฏ Whatโ€™s Next?

Now you can try:

  • ๐Ÿ“š Setting up DHCP reservations and static assignments
  • ๐Ÿ› ๏ธ Configuring DHCP relay for multiple subnets
  • ๐Ÿค Implementing IPv6 DHCP (DHCPv6) configuration
  • ๐ŸŒŸ Building network auto-discovery and configuration systems!

Remember: Every expert was once a beginner. Youโ€™re doing amazing! ๐ŸŽ‰

Keep practicing and youโ€™ll become a networking expert too! ๐Ÿ’ซ