How to set a default gateway on CentOS 6

Last updated on August 19, 2020 by Dan Nanni

A default gateway is a remote host or router that your Linux host forwards traffic to when the destination IP address of outgoing traffic does not match any route in your local routing table.

This post describes how you can change a default gateway on CentOS 6 or earlier system.

Change a Default Gateway Temporarily

If you wish to change a default gateway temporarily at run time, you can use ip command.

First things first. To check what default gateway you are using currently:

$ ip route show
192.168.91.0/24 dev eth0  proto kernel  scope link  src 192.168.91.128 
169.254.0.0/16 dev eth0  scope link  metric 1002 
default via 192.168.91.2 dev eth0 

According to the local routing table shown above, a default gateway is 192.168.91.2, and traffic is forwarded to the gateway via eth0.

In order to change a default gateway to another IP address:

$ sudo ip route replace default via 192.168.91.10 dev eth0

Obviously, a default gateway's IP address should come from the subnet associated with the interface connected to the default gateway, in this example, 192.168.91.0/24. Otherwise, the command will fail with the following error.

RTNETLINK answers: No such process

Also, keep in mind that the default route change made by ip command will be lost after rebooting.

Change a Default Gateway Permanently

In order to set a default gateway permanently, you will need to update /etc/sysconfig/network accordingly.

$ sudo vi /etc/sysconfig/network
GATEWAY=192.168.91.10

Again, be aware that the IP addressed specified here should match with the subnet (192.168.91.0/24) associated with a default route interface.

Another option to set a default gateway persistently on CentOS is to edit /etc/sysconfig/network-scripts/ifcfg-<default_interface_name>, and add GATEWAY=<gateway_ip> there. If the default interface is eth0, you will need to edit /etc/sysconfig/network-scripts/ifcfg-eth0. If you choose to use this method, you need to refer to this post to get familiar with this option.

Whether you edit /etc/sysconfig/network or /etc/sysconfig/network-scripts/ifcfg-XXX, don't forget to restart network service as follows, or reboot your CentOS for the change to take effect.

$ sudo service network restart

Support Xmodulo

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 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean