一、簡介
Linux系統的route命令用於顯示和操作IP路由表(show / manipulate the IP routing table)。要實現兩個不同的子網之間的通信,需要一台連接兩個網絡的路由器,或者同時位於兩個網絡的網關來實現。在Linux系統中,設置路由通常是為了解決以下問題:該Linux系統在一個局域網中,局域網中有一個網關,能夠讓機器訪問Internet,那么就需要將這台機器的IP地址設置為Linux機器的默認路由。要注意的是,直接在命令行下執行route命令來添加路由,不會永久保存,當網卡重啟或者機器重啟之后,該路由就失效了;可以在/etc/rc.local中添加route命令來保證該路由設置永久有效。
二、路由知識
1)靜態路由
靜態路由是手動設置的路由。
如ip route 192.168.1.1 255.255.255.255 192.168.1.254,這條靜態路由的含義是把目的地為192.168.1.1的IP的數據全部轉發至192.168.1.254
2)默認路由
默認路由是其他路由規則都沒有匹配到時,才會選擇使用的路由。 如:ip route 0.0.0.0 0.0.0.0 192.168.1.1,這條默認路由的含義是如果其他路由規則不匹配,就把數據轉發至192.168.1.1
3)靜態默認路由
一般的默認路由都是靜態的。
4)動態默認路由
這個和靜態的默認路由又有什么區別呢?比如有一個星形拓撲,R1為核心路由器,而剩下的R2,R3為分支,想要讓R1告訴分支路由器,當找不到路徑到達一個遠程網絡時候,全部通過核心路由器來轉發數據到遠程網絡。但是當有新的路由器加入到這個網絡拓撲的時候,這個路由器也能通過核心路由器發現核心路由器上的默認路由,這時候的默認路由則是動態的(例如:只要是能夠動態得到核心路由器的網絡的所有的路由器都能有這么一條默認路由,如EIGRP 用D*來表示)
三、實例
1)查看當前路由
route –n
2)添加/屏蔽/刪除一條路由
route add -net 224.0.0.0 netmask 240.0.0.0 dev eth0 route add -net 224.0.0.0 netmask 240.0.0.0 reject route del -net 224.0.0.0 netmask 240.0.0.0
3) 添加/刪除設置默認網關
route add default gw 192.168.0.1 route del default gw 192.168.0.1
四、輸出詳解
route命令輸出的路由表字段含義如下: Destination 目標 The destination network or destination host. 目標網絡或目標主機。 Gateway 網關 The gateway address or '*' if none set. 網關地址,如果沒有就顯示星號。 Genmask 網絡掩碼 The netmask for the destination net; '255.255.255.255' for a host destination and '0.0.0.0' for the default route. Flags:總共有多個旗標,代表的意義如下: o U (route is up):該路由是啟動的; o H (target is a host):目標是一部主機 (IP) 而非網域; o G (use gateway):需要透過外部的主機 (gateway) 來轉遞封包; o R (reinstate route for dynamic routing):使用動態路由時,恢復路由資訊的旗標; o D (dynamically installed by daemon or redirect):已經由服務或轉 port 功能設定為動態路由 o M (modified from routing daemon or redirect):路由已經被修改了; o ! (reject route):這個路由將不會被接受(用來抵擋不安全的網域!) o A (installed by addrconf) o C (cache entry) Metric 距離、跳數。暫無用。 The 'distance' to the target (usually counted in hops). It is not used by recent kernels, but may be needed by routing dae- mons. Ref 不用管,恆為0。 Number of references to this route. (Not used in the Linux ker-nel.) Use 該路由被使用的次數,可以粗略估計通向指定網絡地址的網絡流量。 Count of lookups for the route. Depending on the use of -F and -C this will be either route cache misses (-F) or hits (-C). Iface 接口,即eth0,eth0等網絡接口名 Interface to which packets for this route will be sent.
五、常見錯誤
1)route: netmask doesn't match route address
linux-rd4x:/ # route add -net 8.8.8.8 netmask 255.255.255.0 dev eth0 route: netmask doesn't match route address
提示:
隨意添加一條路由信息時,報錯,經過嘗試,Destination IP必須和掩碼相對應, 即IP:8.8.8.8 & 255.255.255.0(邏輯與操作) 才是真正的DestinationIP,否則會報錯。
2)SIOCADDRT: 沒有那個進程(No Such Process)
route add -net 192.168.1.0 netmask 255.255.255.0 SIOCADDRT: 沒有那個設備
提示:
在添加一個新的網段時,它的出口地址應該是當前ip routing table表中的當前有的地址,否則會出現這個錯誤:SIOCADDRT: 沒有那個進程。