How can i keep an entry in my routing table, even when the associated interface goes down?

Posted on

Problem :

I have a linux box set up as my internet router. I have the eth0 interface connected to the lan, and the eth1 interface connected to a pppoa modem and configured with dhcp to my public ip. Due to issues with ARP i have to connect to the internet using the modem itself (which has the ip 172.16.0.1) as the next hop. To do this, i use the following 2 lines:

route add -host 172.16.0.1 dev eth1
route add default gw 172.16.0.1

This usually runs after the interface has been configured with dhcp, and all is well. The problem comes in when the modem gets disconnected, reconnected and allocated a new ip address by my isp. When the dhcpc daemon reconfigured the eth1 interface for the new ip, my routing table loses the entries it needs to get to the internet, meaning i need to enter the 2 route commands over again. Is there a way to force linux to keep the routes, or possibly to have them added automatically when dhcpcd does it’s thing?

A google search for “persistent routes” brings up ways to keep routes across boots, but that’s not what i need.

Solution :

Option 1

You can usually setup default gateway in your DHCP server so whenever it assigns IPs it will also provide a default gateway for clients to use. Consult your DHCP server’s configuration on how to do this.

Option 2

Other way this can be accomplished on the client is by creating an dhcpcd hook in in /usr/lib/dhcpcd/dhcpcd-hooks (directory might be different on slackware but I highly doubt it). Create a new file called 40-route with contents:

route add -host 172.16.0.1 dev eth1
route add default gw 172.16.0.1

Or alternatively this should also work:

ip route add 172.16.0.0/24 via 172.16.0.1

This should execute this command after dhcpcd gets new IP. You have to change 192.168.0.0/24 to what your network is using.

For posterity, here’s what worked for me.

# /lib/dhcpcd/dhcpcd-hooks/40-route
if [ "$reason" = "BOUND" ] && [ "$interface" = "eth1" ]; then
  route add -host 172.16.0.1 dev eth1
  route add default gw 172.16.0.1
fi

Leave a Reply

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