How do i get the default gateway in LINUX given the destination?

Suezy picture Suezy · Jul 30, 2009 · Viewed 71.6k times · Source

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.

Answer

Ali Mezgani picture Ali Mezgani · Aug 4, 2009

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

IP=$(/sbin/ip route | awk '/default/ { print $3 }')
echo $IP