What command can you use to find the Gateway IP Address (ie. home router address) for eth0 in Linux?
I need to get the IP address from a command line app to use in a shell script.
What command can you use to find the Gateway IP Address (ie. home router address) for eth0 in Linux?
I need to get the IP address from a command line app to use in a shell script.
To print out only the default gw IP:
route -n | grep 'UG[ \t]' | awk '{print $2}'
To print out route information on all interfaces:
route -n
or
netstat -rn
ip route show 0.0.0.0/0 dev eth0 | cut -d\ -f3
is my entry :)
You can get the system's default gateway from the output of netstat -r
or route
$ netstat -rn
Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface
192.168.199.0 0.0.0.0 255.255.255.240 U 0 0 0 virbr1
192.168.200.0 0.0.0.0 255.255.255.240 U 0 0 0 virbr2
192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 wlan0
192.168.122.0 0.0.0.0 255.255.255.0 U 0 0 0 virbr0
0.0.0.0 192.168.1.254 0.0.0.0 UG 0 0 0 wlan0
The 0.0.0.0 is your default gateway, pointing to 192.168.1.254 at my place.
I prefer the iproute package:
# get the default route
ip route list | awk ' /^default/ {print $3}'
# get the default route but limit on eth0 (output may be empty)
ip route list dev eth0 | awk ' /^default/ {print $3}'
Since iproute2 4.14.1, you can also output JSON for a lot of commands.
So this would work:
ip -j route show 0.0.0.0/0 dev <interface> | jq -r '.[0].gateway'
In your case:
ip -j route show 0.0.0.0/0 dev eth0 | jq -r '.[0].gateway'
Note that you need jq for this, but depending on your environment that might already be available - I know it was in my case.
The output from route -n or netstat -rn, and search for the destination 0.0.0.0.
anyone shorter than this? =)
ip r | awk '/^def/{print $3}'
netstat -rn |awk '{if($1=="0.0.0.0") print $2}'
this will cleanly print the gateway IP. (what would linux scripting be without awk?)
If you would like to get the gateway from the interfaces file:
#!/bin/bash
gateway=$(grep -P '^\tgateway' /etc/network/interfaces)
gateway=$(echo ${gateway:9}) # Remove " gateway "
echo "gateway = $gateway"
if [ $gateway == "" ]; then
echo "gateway is blank"
exit -1
fi
My one liner command to get the default gateway IP address :
route | grep default | awk '{print $2}'
Open Terminal on your Linux OS It’s usually located in the top bar or bottom bar, depending on the Linux distribution you use Once you have opened the Terminal window, enter the following commands “ip route | grep default” Now wait a second for the output and note your default gateway address on the screen Your gateway address should look something like 192.168.1.1. Once you know it, you can start configuring your router via its web admin panel.
If this didn't fix your network, you may need a new router.