route命令

路由条目类型

  • 主机路由:目标地址为单个IP。
  • 网络路由:目标地址为IP网络。
  • 默认路由:目标为任意主机,0.0.0.0/0.0.0.0。

用法,查看帮助

# man route

-v, --verbose:be verbose
-n, --numeric:don't resolve names
-ee, --extend:display other/more information
add:add a new route.
del:delete a route.
-net:the target is a network.
-host:the target is a host.
netmask|NM:when adding a network route, the netmask to be used.
gw|GW:route packets via a gateway.
dev:If force the route to be associated with the specified device, as the kernel will try to determine the device on its own. 可以不指定,内核会自己判断用哪块网卡

添加路由

# route add -net 0.0.0.0/0.0.0.0 gw 192.168.10.1
# route add default gw 192.168.10.1

# route add -net 192.56.76.0 netmask 255.255.255.0 dev eth0
  adds a route to the local network 192.56.76.x via "eth0". The word "dev" can be omitted here.  

删除路由

# route del default
    deletes the current default route, which is labeled "default" or 0.0.0.0 in the destination field of the current routing table.

# route del -net 10.0.0.0/8 gw 192.168.10.1 

查看路由表

# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.1.254   0.0.0.0         UG    0      0        0 eth0
0.0.0.0         122.14.206.1    0.0.0.0         UG    0      0        0 eth1
122.14.206.0    0.0.0.0         255.255.254.0   U     0      0        0 eth1
192.168.0.0     0.0.0.0         255.255.240.0   U     0      0        0 eth0

各字段含义

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. 目标网络的掩码,默认路由的掩码为0.0.0.0。

Flags:Possible flags include
      U (route is up):该路由是启动的。
      H (target is a host):目标是一个主机。
      G (use gateway):使用外部网关。
      R (reinstate route for dynamic routing):使用动态路由时,恢复路由。
      D (dynamically installed by daemon or redirect):
      M (modified from routing daemon or redirect)
      A (installed by addrconf)
      C (cache entry)
      !  (reject route):该路由被拒绝,用来抵挡不安全的网域。

Metric:The 'distance' to the target (usually counted in hops). It is not used by recent kernels, but may be needed by routing daemons. 距离、跳数。
Ref:Number of references to this route. (Not used in the Linux kernel.)
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:Interface to which packets for this route will be sent.

另外,路由表是有顺序的,从上到下匹配。如果在eth0和eth1上分别添加一条一样的路由,比如这样:

# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.10.0    0.0.0.0         255.255.255.0   U     0      0        0 eth0 
192.168.10.0    0.0.0.0         255.255.255.0   U     0      0        0 eth1

这时,数据包都会从eth0传出去。

原文地址:https://www.cnblogs.com/keithtt/p/7482732.html