以下是在家庭網絡中配置Linux DHCP與NAT的步驟,假設使用雙網卡(eth0連接外網,eth1連接內網):
sudo apt update && sudo apt install isc-dhcp-server
sudo yum install dhcp
編輯配置文件 /etc/dhcp/dhcpd.conf
,添加以下內容:
subnet 192.168.1.0 netmask 255.255.255.0 {
range 192.168.1.100 192.168.1.200; # IP地址池
option routers 192.168.1.1; # 網關(Linux內網IP)
option domain-name-servers 8.8.8.8, 8.8.4.4; # DNS服務器
}
range
定義分配的IP范圍,routers
指向Linux的LAN口IP,需與內網接口IP一致。編輯 /etc/default/isc-dhcp-server
(Debian/Ubuntu)或 /etc/sysconfig/dhcpd
(CentOS/RHEL),設置:
INTERFACESv4="eth1" # 僅監聽內網接口
sudo systemctl start isc-dhcp-server # Debian/Ubuntu
sudo systemctl start dhcpd # CentOS/RHEL
sudo systemctl enable isc-dhcp-server # 開機自啟
編輯 /etc/sysctl.conf
,取消注釋或添加:
net.ipv4.ip_forward=1
生效配置:
sudo sysctl -p
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
sudo iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT # 允許內網到外網
sudo iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT # 允許已建立的連接返回
sudo iptables-save > /etc/iptables/rules.v4
sudo service iptables save
或 iptables-save > /etc/sysconfig/iptables
ipconfig
(Windows)或 ifconfig
(Linux/macOS)查看是否獲取到IP(應在192.168.1.100-200
范圍內),且網關為192.168.1.1
。ping 8.8.8.8
或訪問網頁,確認可正常訪問互聯網。sudo iptables -t nat -L -n -v
,確認POSTROUTING
鏈中有MASQUERADE
規則。eth0/eth1
替換為實際接口名(如wlan0
),可通過 ip addr
查看。ufw
或firewalld
,需額外放行DHCP(UDP 67/68)和NAT規則。eth0
配置PPPoE客戶端(如pppoeconf
),并調整NAT規則的目標接口為撥號接口。參考來源:[1,2,3,5,6,7,8,9,10,13,15]