14.12 修改IP路由表
route
route
命令不仅能够用于显示路由表,还可以对它进行修改。不过,修改时要小心,否则可能破坏网络,使你的计算机上不了网。
假设你的计算机一直与网关连接不畅,任何数据包都不能有效地离开局域网访问因特网(我的系统曾经真的发生过这种情况)。运行route
命令,确认网关真的是找不着了,然后使用route
命令把网关添加到路由表中(虽然普通用户可以查看路由表,但对它进行修改则需要具有root权限)。
# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.0.0 * 255.255.255.0 U 0 0 0 eth0
# route add -net default gw 192.168.0.1 dev eth0
# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric
➥Ref Use Iface
192.168.0.0 * 255.255.255.0 U 0 0 0 eth0
default 192.168.0.1 0.0.0.0 UG 0 0 0 eth0
现在分析一下这个命令。add
表示正在添加一个新的路由(要删除路由,则用del
)。-net
选项告诉内核,正在添加的目标是一个网络,在这个例子中是default
目标。gw
表示想使用位于192.168.0.1的网关对匹配目标(这里是default
,因此使用子网掩码0.0.0.0)的数据包进行路由。最后,dev eth0
指定要使用的设备,在这个例子中使用的是eth0
上的以太网卡。
假设除了以太网卡eth0
,你还有块无线网卡ath0
,想通过该无线网卡访问局域网10.1.xxx.xxxx(该LAN的网络基地址)中的资源,但根本不想让这个无线网卡访问因特网。可以使用以下命令增加一条匹配这些条件的路由规则:
# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric
➥Ref Use Iface
192.168.0.0 * 255.255.255.0 U 0 0 0 eth0
default 192.168.0.1 0.0.0.0 UG 0 0 0 eth0
# route add -net 10.1.0.0 netmask 255.255.0.0 dev ath0
# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric
➥Ref Use Iface
192.168.0.0 * 255.255.255.0 U 0 0 0 eth0
10.1.0.0 * 255.255.0.0 U 0 0 0 ath0
default 192.168.0.1 0.0.0.0 UG 0 0 0 eth0
以上命令先用dev ath0
指定无线网卡,再将子网掩码设置为255.255.0.0
,以便可以正确地进行路由。如果以后又想删除这个路由,则使用以下命令:
# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric
➥Ref Use Iface
192.168.0.0 * 255.255.255.0 U 0 0 0 eth0
10.1.0.0 * 255.255.0.0 U 0 0 0 ath0
default 192.168.0.1 0.0.0.0 UG 0 0 0 eth0
# route del -net 10.1.0.0 netmask 255.255.0.0 dev eth0
# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric
➥Ref Use Iface
192.168.0.0 * 255.255.255.0 U 0 0 0 eth0
default 192.168.0.1 0.0.0.0 UG 0 0 0 eth0
所有命令都一样,除了使用的是del
,而不是add
。啊,真容易!