How do i get the default gateway in LINUX given th

2019-03-08 10:11发布

I'm trying to get the default gateway, using the destination 0.0.0.0

I used this command: netstat -rn | grep 0.0.0.0

And it returned this list:

**Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface<br>
10.9.9.17       0.0.0.0         255.255.255.255 UH        0 0          0 tun0<br>
133.88.0.0      0.0.0.0         255.255.0.0     U         0 0          0 eth0<br>
0.0.0.0         133.88.31.70    0.0.0.0         UG        0 0          0 eth0**<br>

My goal here is to ping the default gateway using destination 0.0.0.0; thus, that is 133.88.31.70; but this one returns a list because of using grep.

How do i get the default gateway only? I will need it for my bash script to identify if net connection is up or not.

标签: shell gateway
14条回答
疯言疯语
2楼-- · 2019-03-08 11:13

For a list of all default gateways, use mezgani's answer, duplicated (and slightly simplified) here:

/sbin/ip route | awk '/^default/ { print $3 }'

If you have multiple network interfaces configured simultaneously, this will print multiple gateways. If you want to select a single known network interface by name (e.g. eth1), simply search for that in addition to filtering for the ^default lines:

/sbin/ip route |grep '^default' | awk '/eth1/ {print $3}'

You can make a script that takes a single network-interface name as an argument and prints the associated gateway:

#!/bin/bash
if [[ $# -ne 1 ]]; then
    echo "ERROR: must specify network interface name!" >&2
    exit 1
fi
# The third argument of the 'default' line associated with the specified
# network interface is the Gateway.
# By default, awk does not set the exit-code to a nonzero status if a
# specified search string is not found, so we must do so manually.
/sbin/ip route | grep '^default' | awk "/$1/ {print \$3; found=1} END{exit !found}"

As noted in the comments, this has the advantage of setting a sensible exit-code, which may be useful in a broader programmatic context.

查看更多
倾城 Initia
3楼-- · 2019-03-08 11:15

You can get the default gateway using ip command like this:

IP=$(/sbin/ip route | awk '/default/ { print $3 }')
echo $IP
查看更多
登录 后发表回答