# 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
| 欄位 | 說明 |
|---|---|
| Destination | 目標網段或主機 |
| Gateway | 閘道位址,「*」表示目標在本機所屬網段、不需路由 |
| Genmask | 網路遮罩 |
| Flags | 標記:U 路由啟用、H 目標為主機、G 指向閘道、R 動態路由恢復的表項、D 由路由後台程式動態安裝、M 由後台程式修改、! 拒絕路由 |
| Metric | 路由距離(Linux 核心未使用) |
| Ref | 引用次數(Linux 核心未使用) |
| Use | 此路由項被查詢的次數 |
| Iface | 對應的輸出介面 |
指向單一 IP 或主機名的記錄,Flags 為 H:
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(route 顯示中常與 U 合併為 UN):
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 -host 10.20.30.148 gw 10.20.30.40 route del -net 10.20.30.40 netmask 255.255.255.248 eth0 route del -net 10.20.30.48 netmask 255.255.255.248 gw 10.20.30.41 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
這樣立刻生效,但重開機會失效。要永久生效,寫入設定檔:
# vi /etc/sysctl.conf net.ipv4.ip_forward = 1
查詢目前狀態:
# sysctl net.ipv4.ip_forward
若程式需要明確指定從哪一張網卡出去(系統上有 eth0、ppp0、eth1、ra0 等多張),可以用 SO_BINDTODEVICE 把 socket 綁定到該介面:
struct ifreq if_ppp0;
switch(type)
{
case NET_CARD_ETH0:
strncpy(if_ppp0.ifr_name, "eth0", IFNAMSIZ);
break;
case NET_CARD_PPP0:
strncpy(if_ppp0.ifr_name, "ppp0", IFNAMSIZ);
break;
case NET_CARD_ETH1:
strncpy(if_ppp0.ifr_name, "eth1", IFNAMSIZ);
break;
case NET_CARD_RA0:
strncpy(if_ppp0.ifr_name, "ra0", IFNAMSIZ);
break;
default:
errorPrintf(PRT_NET, "input netcart type error...\n");
return -1;
}
if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, (char *)&if_ppp0, sizeof(if_ppp0)) < 0)
{
errorPrintf(PRT_NET, "SO_BINDTODEVICE error...\n");
}
需要留意的是,route 的設定重開機後會消失,多網卡環境下建議寫進 /etc/sysconfig/network-scripts/route-ethX 這類檔案中,讓設定持久化。