How to find the default gateway on Linux

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 send traffic to its default gateway 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 the 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, 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 as follows.

#!/bin/sh

default_gateway_ip=`ip route show | grep 'default' | awk '{print $3}'`

Subscribe to Xmodulo

Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.


Support Xmodulo

Did you find this tutorial helpful? Then please be generous and support Xmodulo!

The following two tabs change content below.
Dan Nanni is the founder and also a regular contributor of Xmodulo.com. He is a Linux/FOSS enthusiast who loves to get his hands dirty with his Linux box. He likes to procrastinate when he is supposed to be busy and productive. When he is otherwise free, he likes to watch movies and shop for the coolest gadgets.

One thought on “How to find the default gateway on Linux

Leave a comment

Your email address will not be published. Required fields are marked *