Persistent WAN IPv4 Address (Best Effort)

Hello to you.

If you’re like me and run lots of services behind your routers you need a lot of dynamic DNS updates whenever your public IP address changes.

That usually works, but there is always a delay and in my case, more often than not, the updates to the DNS secondary server also don’t always work.

Preferable would be not to have to do any DNS updates at all.

Years ago, when I still was on cable, my IP sometimes lasted for a year or even more.
But nowadays only the slightest hick-up on my WAN will change my IP.

I don’t know why that changed, since it depends on so many factors on your router side and on your ISP side.

So here is what I did to up my chances to get the same IP again.

#!/usr/bin/env ash
# shellcheck shell=dash
#
# Writes the current WAN interface IPv4 address into the UCI configuration.
# This is to try to get the same address, the next time a DHCP request to your
# ISP is made.
#
# Since its is written in the static OpenWrt network configuration, it will be
# persistent across reboots, besides network restarts or outages.
#
# This is a best effort approach to avoid getting a new IPv4 address, which
# might need dynamic DNS updates.
# Note that your ISP might not be willing or able to give you the same address.
#
# By placing this script into /etc/udhcpc.user.d/ it will be called after DHCP
# requests to your ISP.
#
# Compatible with OpenWrt and Turris OS.
#

# Get the WAN interface name from UCI
WAN_INTERFACE=$(uci get network.wan.device)

# Get the current WAN IP address
CURRENT_IP=$(ip -4 addr show "$WAN_INTERFACE" | awk '/inet/ {print $2}' | cut -d/ -f1)

# Get the configured IP address from UCI
CONFIGURED_IP=$(uci get network.wan.ipaddr 2>/dev/null)

# Check if the current IP address is different from the configured IP address
if [ "$CURRENT_IP" != "$CONFIGURED_IP" ]; then

    # Update the UCI configuration with the new IP address
    uci set network.wan.ipaddr="$CURRENT_IP"
    uci commit network

fi

Side notes:

  • I also added option norelease '1'
    to the WAN interface configuration in /etc/config/network without knowing what its implications really are.

  • I also tried to set clientid and vendorid options there, which lead to udhcpc crashing and the WAN not working at all, until I removed them again.

But now it seems to work well with my ISP.
Your mileage may vary.