温馨提示×

linux dhcp怎么配置

小樊
54
2026-09-18 21:40:03
栏目: 智能运维

在 Linux 上配置 DHCP,通常分为 DHCP 服务器(提供地址) 和 DHCP 客户端(获取地址) 两种情况。下面分别说明。


一、Linux 作为 DHCP 客户端(自动获取 IP)

1. 使用 NetworkManager(最常见,桌面/服务器通用)

nmcli device show eth0
nmcli con mod eth0 ipv4.method auto
nmcli con up eth0

2. 使用 dhclient(传统方式)

dhclient eth0

3. Ubuntu / Debian(/etc/network/interfaces)

auto eth0
iface eth0 inet dhcp

然后:

ifup eth0

4. RHEL / CentOS(网卡配置文件)

BOOTPROTO=dhcp
ONBOOT=yes
systemctl restart NetworkManager

二、Linux 作为 DHCP 服务器(分配 IP)

以 ISC DHCP Server(dhcpd) 为例。

1. 安装 DHCP 服务

Ubuntu / Debian

apt update
apt install isc-dhcp-server

CentOS / RHEL

yum install dhcp
# 或
dnf 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;
  option subnet-mask 255.255.255.0;
  default-lease-time 600;
  max-lease-time 7200;
}

host server01 {
  hardware ethernet 00:11:22:33:44:55;
  fixed-address 192.168.1.50;
}

3. 指定监听网卡(Ubuntu)

/etc/default/isc-dhcp-server
INTERFACESv4="eth0"

4. 启动 DHCP 服务

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

查看状态:

systemctl status isc-dhcp-server

三、常见问题

1. 端口被占用(dnsmasq)

如果系统已运行 dnsmasq:

systemctl stop dnsmasq
systemctl disable dnsmasq

2. 防火墙放行 DHCP

firewall-cmd --add-service=dhcp --permanent
firewall-cmd --reload

3. 查看租约

cat /var/lib/dhcp/dhcpd.leases

四、简易替代方案(dnsmasq)

如果你只是想给局域网分配 IP:

apt install dnsmasq
dhcp-range=192.168.1.100,192.168.1.200,12h
systemctl restart dnsmasq

如果你能说明:

  • 用的是 Ubuntu / CentOS / Debian?
  • 是 做服务器还是客户端?
  • 是否 云服务器 / 虚拟机 / 物理机?

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

0 踩