內(nèi)容提要
使用下面的 route 命令可以查看 Linux 內(nèi)核路由表。
$ routeKernel IP routing tableDestination Gateway Genmask Flags Metric Ref Use Ifacelocalnet * 255.255.255.0 U 0 0 0 eth0default 192.168.0.1 0.0.0.0 UG 0 0 0 eth0
route 命令的輸出項(xiàng)說(shuō)明
主機(jī)路由是路由選擇表中指向單個(gè)IP地址或主機(jī)名的路由記錄。主機(jī)路由的Flags字段為H。例如,在下面的示例中,本地主機(jī)通過(guò)IP地址192.168.1.1的路由器到達(dá)IP地址為10.0.0.10的主機(jī)。
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
網(wǎng)絡(luò)路由是代表主機(jī)可以到達(dá)的網(wǎng)絡(luò)。網(wǎng)絡(luò)路由的Flags字段為N。例如,在下面的示例中,本地主機(jī)將發(fā)送到網(wǎng)絡(luò)192.19.12的數(shù)據(jù)包轉(zhuǎn)發(fā)到IP地址為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
當(dāng)主機(jī)不能在路由表中查找到目標(biāo)主機(jī)的IP地址或網(wǎng)絡(luò)路由時(shí),數(shù)據(jù)包就被發(fā)送到默認(rèn)路由(默認(rèn)網(wǎng)關(guān))上。默認(rèn)路由的Flags字段為G。例如,在下面的示例中,默認(rèn)路由是IP地址為192.168.1.1的路由器。
Destination Gateway Genmask Flags Metric Ref Use Iface----------- ------- ------- ----- ------ --- --- -----default 192.168.1.1 0.0.0.0 UG 0 0 0 eth0
設(shè)置和查看路由表都可以用 route 命令,設(shè)置內(nèi)核路由表的命令格式是:
route [add|del] [-net|-host] target [netmask Nm] [gw Gw] [[dev] If]
route 命令的參數(shù)說(shuō)明
添加到主機(jī)的路由
sudo route add -host 192.168.1.2 dev eth0:0sudo route add -host 10.20.30.148 gw 10.20.30.40
添加到網(wǎng)絡(luò)的路由
sudo route add -net 10.20.30.40 netmask 255.255.255.248 eth0sudo route add -net 10.20.30.48 netmask 255.255.255.248 gw 10.20.30.41sudo route add -net 192.168.1.0/24 eth1
添加默認(rèn)路由
sudo route add default gw 192.168.1.1
刪除路由
sudo route del -host 192.168.1.2 dev eth0:0sudo route del -host 10.20.30.148 gw 10.20.30.40sudo route del -net 10.20.30.40 netmask 255.255.255.248 eth0sudo route del -net 10.20.30.48 netmask 255.255.255.248 gw 10.20.30.41sudo route del -net 192.168.1.0/24 eth1sudo route del default gw 192.168.1.1
在 Ubuntu 中默認(rèn)的內(nèi)核配置已經(jīng)包含了路由功能,但默認(rèn)并沒(méi)有在系統(tǒng)啟動(dòng)時(shí)啟用此功能。開(kāi)啟 Linux 的路由功能可以通過(guò)調(diào)整內(nèi)核的網(wǎng)絡(luò)參數(shù)來(lái)實(shí)現(xiàn)。要配置和調(diào)整內(nèi)核參數(shù)可以使用 sysctl 命令。例如:要開(kāi)啟 Linux 內(nèi)核的數(shù)據(jù)包轉(zhuǎn)發(fā)功能可以使用如下的命令。
sudo sysctl -w net.ipv4.ip_forward=1
這樣設(shè)置之后,當(dāng)前系統(tǒng)就能實(shí)現(xiàn)包轉(zhuǎn)發(fā),但下次啟動(dòng)計(jì)算機(jī)時(shí)將失效。為了使在下次啟動(dòng)計(jì)算機(jī)時(shí)仍然有效,需要將下面的行寫入配置文件/etc/sysctl.conf。
net.ipv4.ip_forward = 1
用戶還可以使用如下的命令查看當(dāng)前系統(tǒng)是否支持包轉(zhuǎn)發(fā)。
sysctl net.ipv4.ip_forward
聯(lián)系客服