Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Linux 路由表全解析:三種路由類型與 route 指令實戰

要檢視 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

輸出欄位怎麼看

  • Destination:目標網段或主機。
  • Gateway:下一跳網關;顯示 * 代表目標就在本機所在網段,不必繞經路由。
  • Genmask:目標的網路遮罩。
  • Flags:路由狀態標記,常見的有 U(路由啟用中)、H(目標為單一主機)、G(需經網關轉送)、R(動態路由回復的表項)、D(由路由背景程序動態安裝)、M(由背景程序修改)、!(拒絕路由)。
  • Metric:路由距離,即到達目標所需的中繼站數(Linux 核心目前未使用)。
  • Ref:引用次數(核心未使用)。
  • Use:此表項被查詢的次數。
  • Iface:對應的輸出介面。

三種路由類型

主機路由

指向單一 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 設定靜態路由

查詢與設定共用同一支指令,語法如下:

# 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
Copyright © Linux教程網 All Rights Reserved