set default gateway in linux

How to Set Default Gateway in Linux

Your default gateway is the IP address of your router, automatically detected by your OS. But sometimes you may need to set it manually. You can easily do this using route command that allows you to display or change the IP routing table. It is mainly created to setup static IP addresses for your system, hosts, or networks. In this article, we will look at how to set default gateway in Linux.


How to Set Default Gateway in Linux

Here is the syntax to use route command

route [options]

If you simply run route command without any options, it will display the current routing table.

$ route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.1.0     *               255.255.255.0   U     0      0        0 ra0
default         dsl-router      0.0.0.0         UG    0      0        0 ra0

In case of above output, the row with Destination as default is for default gateway. In this case, the default Gateway value is dsl-router.

If you use -n option, you will see the output as IP addresses, without displaying their host names using DNS lookup.

$ route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.255.255.0   0.0.0.0         255.255.255.0   U     0      0        0 venet0
0.0.0.0         192.255.255.1   0.0.0.0         UG    0      0        0 venet0

In case of above output, the Destination with IP address 0.0.0.0 is the row for default gateway, with IP address 192.255.255.1.


Add Gateway

Here is the command to add a new gateway.

route add default gw {IP-ADDRESS} {INTERFACE-NAME}

In the above command,

IP-ADDRESS is the IP address of router

INTERFACE-NAME is the name of network interface such as eth0.

If your router IP address is 192.34.45.56 then run the following command to set it as default gateway.

$ route add default gw 192.34.45.56 eth0

You may also set default gateway using interface name.

$ route add default gw dsl-router eth0

You may also use the following command to set default gateway, just update the IP address below with that of your router.

$ ip route add 192.34.45.56/24 dev eth0

If you find that your default gateways it not changing even after the above commands, then try deleting your existing default gateway first using the following command, and then run the above commands to set it afresh. Specify the IP address of your present default gateway below in place of 192.255.255.0.

route delete default gw 192.255.255.0 eth0

That’s it. You may also use GUI tools like network-admin to set default gateway in Linux.

Also read:

How to Touch All Files in Directory in Linux
How to Exit For Loop in Shell Script
How to Set Default Python Version in Linux
How to Install MediaWiki with NGINX in Ubuntu
How to Send Email with Attachment in Linux

Leave a Reply

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