Dynamic IPv4 gateway value for static route

I have the requirement of setting multiple static routes for a WAN that has a dynamic IP, which means the IPv4 gateway changes. It doesn't change constantly, but can change, as the IP address is not truly static.

I have to set the IPv4 gateway otherwise the routes don't work, is there any way to make the IPv4 gateway value dynamic?

I'm aware this goes against the whole "static" route nature I know! I'm wondering if there is a way to get the gateway dynamically, or automatically have it update if it changes through scripting or similar.

1 Like
cat << "EOF" > /etc/hotplug.d/iface/10-route-update
. /lib/functions/network.sh
network_flush_cache
NET_IF="wan"
network_get_gateway NET_GW "${NET_IF}"
if [ "${ACTION}" = "ifup" -o "${ACTION}" = "ifupdate" ] \
&& [ "${INTERFACE}" = "${NET_IF}" ]
then
    uci set network.@route[0].gateway="${NET_GW}"
    /etc/init.d/network reload
fi
EOF

https://openwrt.org/docs/guide-user/base-system/hotplug

1 Like

Thanks for this! This looks to be just what I need!

For some reason network_find_wan seems to select a network interface which isn't my primary WAN though. I am multihomed, so it's picking up another WAN interface, but not the one I want. My primary WAN has the lowest metric set on the interface, but is there something specific I need to set to make sure it uses the right one?

Could I hard code it to the specific interface?

Edit: Hard coding network_get_gateway with the wan interface works.

1 Like
# Replace
network_find_wan NET_IF

# With
NET_IF="wan"
2 Likes

Thanks! That's what I ended up doing, just commented out the network_find_wan line and hardcoded it with what you've suggested. Not sure why network_find_wan is pulling the interface it is, but I'm fine with hard coding it, given the static routes to be updated are for only for this specific WAN interface anyway

Thanks again!

1 Like

The automatic WAN interface identification is based on the current default route.
So it is required to be specified manually if you are using something like VPN or multi-WAN.

Good to know! I am multihomed, so do have multi WAN interfaces. The WAN required for this is the default route and has the lowest metric, but mwan3 is enabled, so maybe it is skewing the result. Either way hard coding NET_IF works fine for me!

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.