温馨提示×

如何在 Linux 配置 DHCP

小樊
44
2026-08-31 19:56:57
栏目: 智能运维

在 Linux 上配置 DHCP,通常有两种场景:

  1. 把 Linux 配置成 DHCP 客户端(自动获取 IP)
  2. 把 Linux 配置成 DHCP 服务器(给其它设备分配 IP)

下面分别说明。


一、Linux 作为 DHCP 客户端(最常见)

1. 使用 NetworkManager(桌面/服务器常用)

nmcli device show eth0
nmcli connection modify eth0 ipv4.method auto
nmcli connection up eth0

2. 使用 dhclient(传统方式)

sudo dhclient eth0

3. 使用 systemd-networkd

编辑:

/etc/systemd/network/eth0.network

内容:

[Match]
Name=eth0

[Network]
DHCP=yes

然后:

sudo systemctl restart systemd-networkd

二、Linux 作为 DHCP 服务器(如 isc-dhcp-server)

1. 安装 DHCP 服务

Debian / Ubuntu

sudo apt update
sudo apt install isc-dhcp-server

CentOS / Rocky / Alma

sudo yum install dhcp-server

2. 配置 DHCP 服务

编辑配置文件:

/etc/dhcp/dhcpd.conf

示例配置:

subnet 192.168.1.0 netmask 255.255.255.0 {
  range 192.168.1.100 192.168.1.200;
  option routers 192.168.1.1;
  option domain-name-servers 8.8.8.8, 8.8.4.4;
  default-lease-time 600;
  max-lease-time 7200;
}

3. 指定监听网卡

编辑:

/etc/default/isc-dhcp-server

(Ubuntu)

INTERFACESv4="eth0"

4. 启动 DHCP 服务

sudo systemctl enable isc-dhcp-server
sudo systemctl start isc-dhcp-server

查看状态:

sudo systemctl status isc-dhcp-server

三、常见问题排查

  • 防火墙放行 DHCP(UDP 67/68)
sudo ufw allow 67/udp
  • 查看租约:
cat /var/lib/dhcp/dhcpd.leases
  • 确保网卡已配置静态 IP(服务器本身不能是 DHCP 获取)

如果你能说明:

  • 使用的 Linux 发行版
  • 是做客户端还是服务器
  • 是否在虚拟机 / 容器 / 路由器环境

我可以给你更精确的配置示例。

0