要檢視 Linux 核心目前的路由表,最直接的方式就是執行 route:
# route
Destination Gateway Genmask Flags Metric Ref Use Iface 192.168.0.0 * 255.255.255.0 U 0 0 0 eth0 169.254.0.0 * 255.255.0.0 U 0 0 0 eth0 default 192.168.0.1 0.0.0.0 UG 0 0 0 eth0
* 代表目標就在本機所在網段,不必繞經路由。指向單一 IP 或主機名的記錄,Flags 為 H。例如要經由 192.168.1.1 這台路由器抵達 10.0.0.10:
Destination Gateway Genmask Flags Metric Ref Use Iface 10.0.0.10 192.168.1.1 255.255.255.255 UH 0 0 0 eth0
代表本機可抵達的整個網段,Flags 為 N。例如把送往 192.19.12 網段的封包轉交給 192.168.1.1:
Destination Gateway Genmask Flags Metric Ref Use Iface 192.19.12 192.168.1.1 255.255.255.0 UN 0 0 0 eth0
當路由表中找不到符合的目標時,封包一律交給預設路由,Flags 為 G:
Destination Gateway Genmask Flags Metric Ref Use Iface default 192.168.1.1 0.0.0.0 UG 0 0 0 eth0
查詢與設定共用同一支指令,語法如下:
# route [add|del] [-net|-host] target [netmask Nm] [gw Gw] [[dev] If]
其中 add 新增、del 刪除;-net 表示目標是網段、-host 表示目標是主機;netmask 指定遮罩、gw 指定轉送網關、dev 指定輸出介面。
# route add -host 192.168.1.2 dev eth0 # route add -host 10.20.30.148 gw 10.20.30.40
# route add -net 10.20.30.40 netmask 255.255.255.248 eth0 # route add -net 10.20.30.48 netmask 255.255.255.248 gw 10.20.30.41 # route add -net 192.168.1.0/24 eth1
# route add default gw 192.168.1.1
# route del -host 192.168.1.2 dev eth0:0 # route del -net 10.20.30.40 netmask 255.255.255.248 eth0 # route del -net 192.168.1.0/24 eth1 # route del default gw 192.168.1.1
CentOS 的核心預設已具備轉送能力,但開機時並未啟用。要即時打開,可用 sysctl 調整核心參數:
# sysctl -w net.ipv4.ip_forward=1
這種寫法重開機就會失效。若要永久生效,請在 /etc/sysctl.conf 中補上一行:
net.ipv4.ip_forward = 1
隨時想確認目前狀態,直接查詢即可:
# sysctl net.ipv4.ip_forward