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.
use command below:
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:then reference the variable
${IP}
.It would be better to use awk instead of cut here... i.e.:
works on any linux:
The following command returns the default route gateway IP on a Linux host using only bash and awk:
This should even work if you have more than one default gateway as long as their metrics are different (and they should be..).
This simple perl script will do it for you.
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:
or if you need it inside a bash expression:
Good luck.
netstat -rn | grep 0.0.0.0 | awk '{print $2}' | grep -v "0.0.0.0"