Answers:
使用ip route get
。从配置网络路由开始:
该
ip route get
命令是一项有用的功能,可让您查询系统将发送数据包以到达指定IP地址的路由,例如:
# ip route get 23.6.118.140
23.6.118.140 via 10.0.2.2 dev eth0 src 10.0.2.15
cache mtu 1500 advmss 1460 hoplimit 64
在此示例中,通过网关10.0.2.2从eth0接口发送到23.6.118.140的数据包。
ip
软件包。
将以下脚本保存在有用的位置。用您要测试的IP地址调用它,它将告诉您相应的路由。
#!/bin/bash
#
# Find the appropriate routing entry for a given IP address
########################################################################
########################################################################
# Calculate the base network address for a given addres and netmask
#
baseNet() {
local ADDRESS="$1" NETMASK="$2"
ipcalc -nb "$ADDRESS" "$NETMASK" | awk '$1=="Network:"{print $2}'
}
########################################################################
# Go
#
for IPADDRESS in "$@"
do
netstat -rn |
tac |
while read DESTINATION GATEWAY GENMASK FLAGS MSS WINDOW IRTT IFACE
do
NSBASENET=$(baseNet "$DESTINATION" "$GENMASK")
IPBASENET=$(baseNet "$IPADDRESS" "$GENMASK")
if test "X$NSBASENET" = "X$IPBASENET"
then
if test '0.0.0.0' = "$GATEWAY"
then
echo "Matches $DESTINATION with netmask $GENMASK directly on $IFACE"
else
echo "Matches $DESTINATION with netmask $GENMASK via $GATEWAY on $IFACE"
fi
break
fi
done
done
# All done
#
exit 0
用法示例
./what-route.sh 10.0.5.6
Matches 0.0.0.0 with netmask 0.0.0.0 via 10.0.2.2 on eth0
./what-route.sh 10.0.2.6
Matches 10.0.2.0 with netmask 255.255.255.0 directly on eth0