route (net-tools 套件) 為傳統路由表管理工具,現代系統推薦使用 ip route (iproute2 套件) 功能更強、輸出更易解析。本文兼顧兩者說明。
route -n / ip route show)# route -n 輸出範例
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 192.168.1.1 0.0.0.0 UG 100 0 0 eth0
192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
172.17.0.0 0.0.0.0 255.255.0.0 U 0 0 0 docker0
U=Up(啟用) G=Gateway(經網關) H=Host(主機路由) D=Dynamic(動態路由) M=Modified !=Reject(拒絕)。route -n # 數值格式顯示 (快,不做 DNS 反解)
ip route show # 現代格式,更清晰
ip route show table all # 顯示所有路由表 (含 policy routing)
# 傳統 route (臨時,重啟失效)
route add default gw 192.168.1.1
route del default gw 192.168.1.1
# 現代 ip route (推薦)
ip route add default via 192.168.1.1 dev eth0
ip route del default via 192.168.1.1 dev eth0
ip route replace default via 192.168.1.1 dev eth0 # 原子性替換
# 永久生效 (RHEL/CentOS)
echo "GATEWAY=192.168.1.1" >> /etc/sysconfig/network-scripts/ifcfg-eth0
# 永久生效 (Debian/Ubuntu netplan)
# /etc/netplan/01-netcfg.yaml -> routes: - to: default via: 192.168.1.1
# 訪問 10.0.0.0/8 網段走 192.168.1.254 网关
route add -net 10.0.0.0 netmask 255.0.0.0 gw 192.168.1.254 dev eth0
ip route add 10.0.0.0/8 via 192.168.1.254 dev eth0
# 禁用/拒絕某網段 (黑洞路由)
route add -net 192.168.100.0 netmask 255.255.255.0 reject
ip route add blackhole 192.168.100.0/24 # 現代寫法,直接丟棄不回 ICMP
route del -net 10.0.0.0 netmask 255.0.0.0
ip route del 10.0.0.0/8
route add -host 10.10.10.10 gw 192.168.1.5
ip route add 10.10.10.10/32 via 192.168.1.5
根據來源 IP、標記 (fwmark)、TOS 等選擇不同路由表:
# 規則: 來自 192.168.10.0/24 的封包查 table 10
ip rule add from 192.168.10.0/24 table 10 priority 100
# table 10 中定義專屬預設路由
ip route add default via 10.0.0.1 dev eth1 table 10
# 查看規則
ip rule show
| 發行版 | 配置文件 | 關鍵配置範例 |
|---|---|---|
| RHEL/CentOS 7 (network-scripts) | /etc/sysconfig/network-scripts/route-eth0 | 10.0.0.0/8 via 192.168.1.254 dev eth0 |
| RHEL 8/9, Fedora (NetworkManager) | nmcli / /etc/NetworkManager/system-connections/ | nmcli con mod eth0 +ipv4.routes "10.0.0.0/8 192.168.1.254" |
| Debian/Ubuntu (netplan) | /etc/netplan/*.yaml | routes: - to: 10.0.0.0/8 via: 192.168.1.254 |
| 通用 (rc.local 臨時) | /etc/rc.local | ip route add ... (需執行權限) |
ip route get 8.8.8.8 驗證去向特定 IP 的實際路由決策。rp_filter (反向路徑驗證) 是否導致非對稱路由丟包:sysctl net.ipv4.conf.all.rp_filter (建議設 2 鬆散模式)。metric 值,避免預設路由衝突。iptables -t filter -nvL FORWARD / nft list chain inet filter forward 是否允許轉發。