Add a Static Route on CentOS

To add a temporary route:

ip route add 172.16.5.0/24 via 10.0.0.101 dev eth0

To make it persist system or network settings restart, create a route-ifname file for an interface through which the subnet is accessed, in this case eth0:

nano /etc/sysconfig/network-scripts/route-eth0

Add the line with the network settings for the other subnet:

172.16.5.0/24 via 10.0.0.101 dev eth0

If your computer is on a network and is not directly connected to the internet, it will be configured with what is called a default gateway, which is usually a router. If the computer cannot find the specific IP address on its local network (aka broadcast domain), as defined by its subnet, it will forward any packets headed to that IP address to the default gateway. The gateway will then attempt to forward packets elsewhere, such as the internet, or another broadcast domain.

But what if you have a separate network (i.e. another office department) that is NOT accessible via the default gateway?

For example, your internet router may be located at 10.0.0.1 and it is serving your local network, 10.0.0.0/8. However, you have a 172.16.5.0 /24 network that is accessible only through a secondary router, which has the IP address 10.0.0.101 on the main network. Therefore, you need to point your OS to the secondary router for any IP addresses located in the 172.16.5.0-255 address space. To do this, you need to add a static route.

Add a temporary static route

If you wish to add one temporarily, simply run the ip route add command with the right network information:

ip route add 172.16.5.0/24 via 10.0.0.101 dev eth0

172.16.5.0 is the network you wish to access.
/24 is the subnet mask
10.0.0.101 is the secondary router to which you are adding a default route
eth0 is the network interface assigned to your main network (in this case, 10.0.0.0/8)

ip route add command will only persist until the next reboot or interface/network settings restart.

Add a permanent static route

To make the route permament, you need to create a static route configuration file. Create a file with the name route-interface in /etc/sysconfig/network-scripts, such as:

nano /etc/sysconfig/network-scripts/route-eth0

Then, add the same line you would with ip route add:

172.16.5.0/24 via 10.0.0.101 dev eth0

Make sure to restart your network settings so they take effect:

service network restart

If you lose your internet connection
If you suddenly cannot connect to the internet after adding a static route and are using static IPs (as opposed to DHCP), you may not have your default gateway configured correctly. Add it to your /etc/sysconfig/network file:

nano /etc/sysconfig/network
GATEWAY=10.0.0.1
Share

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.