Linux 新增靜態路由常用 route (net-tools) 與 ip route (iproute2) 兩套工具。本文對照兩者語法、永久化方法、常見坑點,並提供雙棧 (IPv4/IPv6) 範例。
| 操作 | route (舊) | ip route (新,推薦) |
|---|---|---|
| 顯示路由表 | route -n | ip route show |
| 新增網路路由 | route add -net 10.0.0.0/8 gw 192.168.1.1 dev eth0 | ip route add 10.0.0.0/8 via 192.168.1.1 dev eth0 |
| 新增主機路由 | route add -host 10.10.10.10 gw 192.168.1.1 | ip route add 10.10.10.10 via 192.168.1.1 |
| 新增預設閘道 | route add default gw 192.168.1.1 | ip route add default via 192.168.1.1 |
| 刪除路由 | route del -net 10.0.0.0/8 | ip route del 10.0.0.0/8 |
| 刪除預設閘道 | route del default | ip route del default |
| 修改路由 | 不支援 (需刪後加) | ip route change 10.0.0.0/8 via 192.168.1.2 |
| 替換路由 | 不支援 | ip route replace 10.0.0.0/8 via 192.168.1.2 |
| 查看快取/統計 | 不支援 | ip route show cache (舊核心)ip route get 8.8.8.8 查詢實際路徑 |
原因:閘道 IP 不在本機直連網段,核心無法解析下一跳 MAC。
解決:確保閘道可直達 (同一 L2 網段),或先加入至閘道的路由。
# /etc/rc.local (需執行權限 chmod +x)
#!/bin/bash
ip route add 192.168.10.0/24 via 192.168.1.254 dev eth0
ip route add 192.168.20.0/24 via 192.168.1.254 dev eth0
exit 0
# /etc/sysconfig/network-scripts/route-eth0
192.168.10.0/24 via 192.168.1.254 dev eth0
192.168.20.0/24 via 192.168.1.254 dev eth0
default via 192.168.1.1 dev eth0
格式:目標網路 via 閘道 dev 介面,每行一條。
# /etc/network/interfaces
auto eth0
iface eth0 inet static
address 192.168.1.10/24
gateway 192.168.1.1
up ip route add 192.168.10.0/24 via 192.168.1.254 dev eth0
down ip route del 192.168.10.0/24 via 192.168.1.254 dev eth0
# /etc/netplan/01-netcfg.yaml (Netplan)
network:
version: 2
renderer: networkd
ethernets:
eth0:
addresses: [192.168.1.10/24]
gateway4: 192.168.1.1
routes:
- to: 192.168.10.0/24
via: 192.168.1.254
- to: 192.168.20.0/24
via: 192.168.1.254
# 臨時
ip -6 route add 2001:db8:1::/64 via fe80::1 dev eth0
# 永久 (route-eth0 格式相同)
2001:db8:1::/64 via fe80::1 dev eth0
# Netplan
routes:
- to: 2001:db8:1::/64
via: fe80::1
# 建立路由表 100, 101
echo "100 isp1" >> /etc/iproute2/rt_tables
echo "101 isp2" >> /etc/iproute2/rt_tables
# 表 100 走 ISP1
ip route add default via 192.168.1.1 dev eth0 table 100
ip rule add from 192.168.1.10/32 table 100
# 表 101 走 ISP2
ip route add default via 192.168.2.1 dev eth1 table 101
ip rule add from 192.168.2.10/32 table 101
ip route show # 主表
ip route show table 100 # 指定表
ip route get 8.8.8.8 from 192.168.1.10 # 模擬查詢實際路徑
ip rule show # 策略規則
traceroute -n 8.8.8.8 # 實測路徑
現代 Linux 統一採用 iproute2 (ip route) 管理路由,語法一致、支援修改/替換/策略路由/雙棧。永久化首選 發行版原生網路配置檔 (route-eth0 / Netplan / interfaces),/etc/rc.local 為通用後備。遇到 Network is unreachable 先驗證閘道 L2 可達性。