tags:

views:

531

answers:

3

Good day!

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 returns this list:

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

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'.

Question is: 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.

Any answers will be much appreciated. =)

+1  A: 

This simple perl script will do it for you.

#!/usr/bin/perl

$ns = `netstat -nr`;

$ns =~ m/0.0.0.0\s+([0-9]+.[0-9]+.[0-9]+.[0-9]+)/g;

print $1

Basically, we run netstat, save it to $ns. Then find the line that starts off with 0.0.0.0. Then the parentheses in the regex saves everything inside it into $1. After that, simply print it out.

If it was called null-gw.pl, just run it on the command like:

perl null-gw.pl

or if you need it inside a bash expression:

echo $(perl null-gw.pl)

Good luck.

Jeremy Powell
thank you! =) I'll try it.. Atleast I do know how to program in Perl.
Suezy
A: 

if you know that 0.0.0.0 is your expected output, and will be at the beginning of the line, you could use the following in your script:

IP=`netstat -rn | grep -e '^0\.0\.0\.0' | cut -d' ' -f2`

then reference the variable ${IP}.

maxwellb
basic point of this approach, use an extended regexp, followed by cut to get your desired field. however, you could use awk as others have posted, but I have yet to learn the language.
maxwellb
+2  A: 

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

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

mezgani