How do i get the default gateway in LINUX given the destination?
You can get the default gateway using ip
command like this:
IP=$(/sbin/ip route | awk '/default/ { print $3 }')
echo $IP
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