WAN in dhcpclient mode but with static IP fallback

Hi,

I need my WAN port to obtain IP from dhcp.

But if for some reason it can't, it should configure itself with pre-determined static IP address. (think, travel router/server)

Here is my plan so far

opkg update
opkg install bash coreutils-nohup
vi /root/dhcp_fallback.sh

/root/dhcp_fallback.sh

#!/bin/bash

# Interface to configure
iface="eth0.2" # Change to your WAN interface

# Static IP configuration
static_ip="192.168.2.1"
netmask="255.255.255.0"
gateway="192.168.2.1"
dns="1.1.1.1"

# Try to get a DHCP lease
udhcpc -i $iface -n -q -t 10
if [ $? -ne 0 ]; then
    # DHCP failed, configure static IP
    ifconfig $iface $static_ip netmask $netmask up

    # Set default route and DNS
    route add default gw $gateway
    echo "nameserver $dns" > /etc/resolv.conf

    # Start DHCP server
    /etc/init.d/dnsmasq start
fi
echo /root/dhcp_fallback.sh & >> /etc/rc.local

Can you explain why you would opt to fall back to a static IP address on the wan if you don't get a DHCP lease?

In the context of a travel router device, you don't know what the upstream network is going to be... if there is no DHCP server, there is usually no upstream network available. Assigning a static IP on the wan has no value if there is no upstream... but even if there is an upstream network available (just no DHCP server or one that won't issue a lease), if you don't know in advance what the subnet of the upstream network actually is (or at least not in advance of you writing your script), you can't guarantee that you'll join the right network. And... worse... if you happen to actually conflict with the upstream router's address, you could cause problems or even bring down the network.

Simply put, if the WAN port doesn't receive a dhcp lease, then it's because there's another client host plugged there.

I agree this should not be the default openwrt config, it's a special use case.

Here are other people asking about that.

The general theme is "dhcpclient with static fallback +optional dhcp server"

https://www.gargoyle-router.com/phpbb/viewtopic.php?t=2053

https://forum.archive.openwrt.org/viewtopic.php?id=21197