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 return
works on any linux:
route -n|grep "UG"|grep -v "UGH"|cut -f 10 -d " "
You can get the default gateway using ip
command like this:
IP=$(/sbin/ip route | awk '/default/ { print $3 }')
echo $IP
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.
netstat -rn | grep 0.0.0.0 | awk '{print $2}' | grep -v "0.0.0.0"
To get the NIC name that it's the default gateway use this command:
netstat -rn | grep UG | awk '{print $8}'
The ip route command from the iproute2 package can select routes without needing to use awk
/grep
, etc to do the selection.
To select the default route (from possibly many)
$ ip -4 route show default # use -6 instead of -4 for ipv6 selection.
default via 172.28.206.254 dev wlp0s20f3 proto dhcp metric 600
To select the next hop for a particular interface
$ ip -4 route list type unicast dev eth0 exact 0/0 # Exact specificity
default via 172.29.19.1 dev eth0
In the case of multiple default gateways, you can select which one gets chosen as the next-hop to a particular destination address.
$ ip route get $(dig +short google.com | tail -1)
173.194.34.134 via 172.28.206.254 dev wlan0 src 172.28.206.66
cache
You can then extract the value using sed
/awk
/grep
, etc. Here is one example using bash
's read
builtin.
$ read _ _ gateway _ < <(ip route list match 0/0); echo "$gateway"
172.28.206.254