Last updated on July 18, 2020 by Dan Nanni
In TCP/IP networking, a default gateway provides a default route for a host to use in order to send traffic to remote networks. Here "default" implies that a host will always rely on this gateway to send traffic to unless it knows how to route the traffic.
To find out what is the default gateway used on Linux, you can refer to a local routing table.
The ip
command shows a local routing table.
$ ip route show
default via 192.168.1.1 dev wlan0 proto static 169.254.0.0/16 dev wlan0 scope link metric 1000 172.16.199.0/24 dev vmnet1 proto kernel scope link src 172.16.199.1 192.168.1.0/24 dev wlan0 proto kernel scope link src 192.168.1.4 metric 9 192.168.233.0/24 dev vmnet8 proto kernel scope link src 192.168.233.1
In the routing table, the row starting with "default via
" shows information about the default route configured on your Linux system. The information includes the IP address of the default gateway, and the network interface reachable to this gateway.
In this example, 192.168.1.1
is the default gateway, and it is reachable via wlan0
network interface.
If you are writing a shell script where you need to obtain the IP address of the default gateway programmatically, the following command can be useful. It will print out the IP address of the default gateway.
$ ip route show | grep 'default' | awk '{print $3}'
192.168.1.1
Thus in your script, you can easily store the IP address of the default gateway to a variable as follows.
#!/bin/sh default_gateway_ip=`ip route show | grep 'default' | awk '{print $3}'`
This website is made possible by minimal ads and your gracious donation via PayPal or credit card
Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.
Xmodulo © 2021 ‒ About ‒ Write for Us ‒ Feed ‒ Powered by DigitalOcean