How to query the default gateway in Linux
I bought a cloud server on cnaaa.
A gateway is an entry point between two networks, and a router is an example of a gateway. All traffic on your network goes to the router, and then through the router to the Internet.
Sometimes you need to know the IP address of the router, the gateway IP is actually the IP address of the router in normal settings.
Next, we use the ip command to display the gateway IP on the command line, open a terminal, and enter the following command:
ip route
You will see the following output:
default via 192.168.0.1 dev wlp58s0 proto dhcp metric 600169.254.0.0/16 dev wlp58s0 scope link metric 1000192.168.0.0/24 dev wlp58s0 proto kernel scope link src 192.168.0.106 metric 600
In the above output, pay attention to the line starting with default, followed by the default gateway IP address.
Alternatively, the above command can be combined with grep:
ip route | grep default
The output of this command will only give the default gateway IP:
default via 192.168.0.1 dev wlp1s0 proto dhcp metric 600
As shown above, 192.168.0.1 is the default gateway IP in our example.
Other Ways to Find Your Gateway IP Address
The ip command in Linux provides most network-related operations. If we have used the Linux system for a while, we may notice that there are generally many different ways to accomplish something. So, there are other ways to check the default gateway, such as using other network command-line tools, which we will take a look at next.
Use the route command to query the gateway address
We can use the -n option in the route command to display the routing table containing the IP addresses as follows:
route -n
The output looks like this:
Kernel IP routing tableDestination Gateway Genmask Flags Metric Ref Use Iface0.0.0.0 192.168.0.1 0.0.0.0 UG 600 0 0 wlp58s0169.254.0.0 0.0.0.0 255.255.0.0 U 1000 0 0 wlp58s0192.168.0.0 0.0.0.0 255.255.255.0 U 600 0 0 wlp58s0
Notice the U and G logos? U means route "up" and G means it's a gateway .
Use the netstat command to query the gateway
We can also obtain the gateway address by using the netstat command to display the routing tables that make up the gateway. See the following command:
netstat -r -n
The output is the same as that of the route command:
Kernel IP routing tableDestination Gateway Genmask Flags MSS Window irtt Iface0.0.0.0 192.168.0.1 0.0.0.0 UG 0 0 0 wlp58s0169.254.0.0 0.0.0.0 255.255.0.0 U 0 0 0 wlp58s0192.168.0.0 0.0.0.0 255.255.255.0 U 0 0 0 wlp58s0
The gateway address can be found through the G flag.