Linux setup default gateway with route command

如何用指令模式設定linux預設閘道器??

在設定 route 之前先顯示一下該機器的 routing table. 可以直接用 route 命令

[USER@Aloha ~]$ route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.5.0     *                   255.255.255.0   U       0      0        0   eth1
10.1.1.0           *                   255.255.255.0   U       0      0        0   eth0
default            10-1-1-254  0.0.0.0               UG     0      0        0   eth0

也當然可以用 route -n 命令. 直接看各個 ip 位址.

[USER@Aloha ~]$ route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.5.0     0.0.0.0          255.255.255.0   U       0      0        0   eth1
10.1.1.0           0.0.0.0          255.255.255.0   U       0      0        0   eth0
0.0.0.0            10.1.1.254     0.0.0.0               UG     0      0        0   eth0

由上面的 routing table 代表要往 192.168.5/24 的介面由 eth1 走 要往 10.1.1/24 的介面網 eth0走.其他不知道的網段就往 eth0 送. 在最後一筆紀錄的 Flags 與其他介面不太一樣. 那個G代表的是gateway. 所以預設閘道器在 eth0 介面.

如果我要將預設閘道器改為 eth1 介面. 我可以用下面兩個指令改變預設閘道器

route add default gw {IP-ADDRESS} {INTERFACE-NAME}

route del default gw {IP-ADDRESS} {INTERFACE-NAME}

[USER@Aloha ~]$ routea del default gw 10.1.1.254 eth0

[USER@Aloha ~]$ routea add default gw 192.168.5.254 eth1

再次列出目前的路由表.

[USER@Aloha ~]$ route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.5.0     0.0.0.0           255.255.255.0   U       0      0        0   eth1
10.1.1.0           0.0.0.0           255.255.255.0   U       0      0        0   eth0
0.0.0.0          192.168.5.254  0.0.0.0               UG     0      0        0   eth1

這樣就改變了 default gateway.

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.