14.12 修改IP路由表

route

route命令不仅能够用于显示路由表,还可以对它进行修改。不过,修改时要小心,否则可能破坏网络,使你的计算机上不了网。

假设你的计算机一直与网关连接不畅,任何数据包都不能有效地离开局域网访问因特网(我的系统曾经真的发生过这种情况)。运行route命令,确认网关真的是找不着了,然后使用route命令把网关添加到路由表中(虽然普通用户可以查看路由表,但对它进行修改则需要具有root权限)。

  1. # route
  2. Kernel IP routing table
  3. Destination Gateway Genmask Flags Metric Ref Use Iface
  4. 192.168.0.0 * 255.255.255.0 U 0 0 0 eth0
  5. # route add -net default gw 192.168.0.1 dev eth0
  6. # route
  7. Kernel IP routing table
  8. Destination Gateway Genmask Flags Metric
  9. Ref Use Iface
  10. 192.168.0.0 * 255.255.255.0 U 0 0 0 eth0
  11. 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的网络基地址)中的资源,但根本不想让这个无线网卡访问因特网。可以使用以下命令增加一条匹配这些条件的路由规则:

  1. # route
  2. Kernel IP routing table
  3. Destination Gateway Genmask Flags Metric
  4. Ref Use Iface
  5. 192.168.0.0 * 255.255.255.0 U 0 0 0 eth0
  6. default 192.168.0.1 0.0.0.0 UG 0 0 0 eth0
  7. # route add -net 10.1.0.0 netmask 255.255.0.0 dev ath0
  8. # route
  9. Kernel IP routing table
  10. Destination Gateway Genmask Flags Metric
  11. Ref Use Iface
  12. 192.168.0.0 * 255.255.255.0 U 0 0 0 eth0
  13. 10.1.0.0 * 255.255.0.0 U 0 0 0 ath0
  14. default 192.168.0.1 0.0.0.0 UG 0 0 0 eth0

以上命令先用dev ath0指定无线网卡,再将子网掩码设置为255.255.0.0,以便可以正确地进行路由。如果以后又想删除这个路由,则使用以下命令:

  1. # route
  2. Kernel IP routing table
  3. Destination Gateway Genmask Flags Metric
  4. Ref Use Iface
  5. 192.168.0.0 * 255.255.255.0 U 0 0 0 eth0
  6. 10.1.0.0 * 255.255.0.0 U 0 0 0 ath0
  7. default 192.168.0.1 0.0.0.0 UG 0 0 0 eth0
  8. # route del -net 10.1.0.0 netmask 255.255.0.0 dev eth0
  9. # route
  10. Kernel IP routing table
  11. Destination Gateway Genmask Flags Metric
  12. Ref Use Iface
  13. 192.168.0.0 * 255.255.255.0 U 0 0 0 eth0
  14. default 192.168.0.1 0.0.0.0 UG 0 0 0 eth0

所有命令都一样,除了使用的是del,而不是add。啊,真容易!