Static Routes

From Leo's Notes
Last edited on 30 December 2021, at 01:49.

How to set static routes on Linux and Windows.

Linux[edit | edit source]

Changing Default Route[edit | edit source]

When dealing with multiple network interfaces, you may want to change the default route from one interface to another.

Suppose we have the following default route (utilizing interface em2 via 10.16.61.49) and we wish to change it to use interface em1 via 192.168.248.100.

# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         10.16.61.49     0.0.0.0         UG    0      0        0 em2

First delete the gateway via em2, then add the new default route via em1. If you do not delete the existing default route first, you will get a RTNETLINK answers: File exists error when attempting to add another default route.

## with old route command:
# route del -net 0.0.0.0 gw 10.16.61.49 netmask 0.0.0.0 dev em2
## or with new ip command:
# ip route del 0.0.0.0/0.0.0.0 via 10.16.61.49

## Add the new default route
# ip route add default via 192.168.248.100 dev em1

Verify that the default route is set.

# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.248.100 0.0.0.0         UG    0      0        0 em1

To make this persistent, create a /etc/sysconfig/network-scripts/route-em2 file with all routes:

10.0.0.0/8 via 10.16.61.49 dev em2
136.159.0.0/16 via 10.16.61.49 dev em2

Temporary Route[edit | edit source]

# ip route add 136.159.9.1 dev eth1
# ip route add 10.0.0.0/8 via 136.159.9.1

This will be wiped away if the network gets restarted or if the machine reboots.

Persistent Routes (RedHat Based)[edit | edit source]

To make your route survive a reboot, ensure that there is a gateway set in /etc/sysconfig/network-scripts/ifcfg-eth1. Eg:

DEVICE="eth1"
BOOTPROTO="static"
ONBOOT="yes"
TYPE="Ethernet"
IPADDR=136.159.9.9
GATEWAY=136.159.9.1
NETMASK=255.255.255.0

Then, define the static routes in /etc/sysconfig/network-scripts/route-eth1:

default 136.159.9.1 dev eth1
10.0.0.0/8 via 136.159.9.1 dev eth1

Windows[edit | edit source]

Use the route command.

Temporary[edit | edit source]

To make 9.11.9.11 route to 10.1.2.2:

C:>route add 9.11.9.11 mask 255.255.255.255 10.1.2.2
 OK!

This route will be lost on a reboot.

Persistent[edit | edit source]

To make a rule persistent, just add -p to the route command.

Eg:

C:>route -p add 9.11.9.11 mask 255.255.255.255 10.1.2.2
 OK!