Route
[root@ip-172-16-1-165 ~]# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default _gateway 0.0.0.0 UG 100 0 0 eth0
default _gateway 0.0.0.0 UG 101 0 0 eth1
172.16.1.0 0.0.0.0 255.255.255.0 U 100 0 0 eth0
172.16.2.0 0.0.0.0 255.255.255.0 U 101 0 0 eth1
Destination | 目标网段或者主机 |
---|---|
Gateway | 网关地址,”*” 表示目标是本主机所属的网络,不需要路由 |
Genmask | 网络掩码 |
Flags | 标记。一些可能的标记如下: |
U — 路由是活动的 | |
H — 目标是一个主机 | |
G — 路由指向网关 | |
R — 恢复动态路由产生的表项 | |
D — 由路由的后台程序动态地安装 | |
M — 由路由的后台程序修改 | |
! — 拒绝路由 | |
Metric | 路由距离,到达指定网络所需的中转数(linux 内核中没有使用) |
Ref | 路由项引用次数(linux 内核中没有使用) |
Use | 此路由项被路由软件查找的次数 |
Iface | 该路由表项对应的输出接口 |
路由的三种类型
主机路由
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
网络路由
网络路由是代表主机可以到达的网络。网络路由的Flags字段为N。例如,在下面的示例中,本地主机将发送到网络192.19.12的数据包转发到IP地址为192.168.1.1的路由器。
Destination Gateway Genmask Flags Metric Ref Use Iface
—————- ———- ———- ——- ——- —- —- ——-
192.19.12.0 192.168.1.1 255.255.255.0 UN 0 0 0 eth0
默认路由
Destination Gateway Genmask Flags Metric Ref Use Iface
—————- ———- ———- ——- ——— —- —- ——-
default 192.168.1.1 0.0.0.0 UG 0 0 0 eth0
route 命令
route [add|del] [-net|-host] target [netmask Nm] [gw Gw] [[dev] If]
- add : 添加一条路由规则
- del : 删除一条路由规则
- -net : 目的地址是一个网络
- -host : 目的地址是一个主机
- target : 目的网络或主机
- netmask : 目的地址的网络掩码
- gw : 路由数据包通过的网关
- dev : 为路由指定的网络接口
Example
到主机路由
#route add -host 192.168.1.2 dev eth0
#route add -host 10.20.30.148 gw 10.20.30.40
到网路路由
# route add -net 10.20.30.40 netmask 255.255.255.248 eth0 #添加10.20.30.40的网络
# route add -net 10.20.30.48 netmask 255.255.255.248 gw 10.20.30.41 #添加10.20.30.48的网络
# route add -net 192.168.1.0/24 eth1
添加默认路由
route add default gw 192.168.1.1
删除路由
# route del -host 192.168.1.2 dev eth0:0
# route del -host 10.20.30.148 gw 10.20.30.40
# route del -net 10.20.30.40 netmask 255.255.255.248 eth0
# route del -net 10.20.30.48 netmask 255.255.255.248 gw 10.20.30.41
# route del -net 192.168.1.0/24 eth1
# route del default gw 192.168.1.1
路由转发
临时生效
echo "1" > /proc/sys/net/ipv4/ip_forward
永久生效
# vi /etc/sysctl.conf
net.ipv4.ip_forward = 1