linux 路由基本命令的使用

Markdown Example

linux route 命令

route 命令可以显示或设置 Linux 内核中的路由表,主要是静态路由
对于局域网中的 Linux 主机,要想访问 Internet,需要将局域网的网关 IP 地址设置为这个主机的默认路由。
在命令行中通过 route 命令添加的路由在网卡重启或机器重启后失效。
可以在 /etc/rc.local 中添加 route 命令来保证路由设置永久有效。

选项:
-A:设置地址类型
-C:打印 Linux 内核的路由缓存
-v:显示详细信息
-n:不执行 DNS 反向查找,直接显示数字形式的 IP 地址
-e:netstat 格式显示路由表
-net:到一个网络的路由表
-host:到一个主机的路由表

参数:
add:增加路由记录
del:删除路由记录
target:目的网络或目的主机
gw:设置默认网关
mss:设置TCP的最大区块长度(MSS),单位MB
window:指定通过路由表的TCP连接的TCP窗口大小
dev:路由记录所表示的网络接口

添加主机路由

添加主机路由时,需要指定网络 ID 和主机 ID,此时需要设置 netmask 255.255.255.255
Flags: UH

$route add -net 10.0.0.10 netmask 255.255.255.255 gw 10.139.128.1 dev eth0
#或
route add -net 10.0.0.10/25 gw 10.139.128.1 dev eth0

route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
10.0.0.10       10.139.128.1    255.255.255.255 UGH   0      0        0 eth0
...

#这里 -net 10.0.0.10/25 是指到达的目标网络网关
#gw 10.139.128.1 指出发的网关或地址
#dev eth0 从本机的哪个网卡设备出发
#总结就是:添加了一条路由、流量本从机的 eth0网卡 到 10.139.128.1 网关,再从改网关去到 目标网络 -net 10.0.0.10/25 

添加网络路由(网关路由)

添加网络路由时,只需指定网络 ID,通过 netmask 设置掩码长度
Flags: UG

$route add -net 10.0.0.0 netmask 255.255.255.0 gw 10.139.128.1 dev eth0

$route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
10.0.0.0        10.139.128.1    255.255.255.0   UG    0      0        0 eth0

添加添加同一个局域网的主机

不指定 gw 选项时,添加的路由记录不使用网关
Flags: U

$route add -net 224.0.0.0 netmask 240.0.0.0 dev eth0

$route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
224.0.0.0       0.0.0.0         240.0.0.0       U     0      0        0 eth0

屏蔽路由

Flags: !

$route add -net 224.0.0.0 netmask 240.0.0.0 reject

route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
224.0.0.0       -               240.0.0.0       !     0      -        0 -

删除路由

#1. 删除可用路由
$route del -net 224.0.0.0 netmask 240.0.0.0

#2. 删除屏蔽的路由
$route del -net 224.0.0.0 netmask 240.0.0.0 reject

#3. 删除和添加设置默认网关
$route add default gw 192.168.1.1
SIOCADDRT: Network is unreachable
$route del default gw 192.168.1.1
SIOCDELRT: No such process

注意:添加或删除默认网关时,Linux 会自动检查网关的可用性

posted @ 2024-07-12 15:23  little小新  阅读(11)  评论(0编辑  收藏  举报