Wireguard for dynamique ip (only with a private server or vps)


I have a 4G router that changes public ip every time I turn it off + another router with openwrt connected at the back + wireguard installed.
The problem is that wireguard keeps in memory the last connection ip, so every time the network is started, no connection to wireguard.

I found a troubleshooting solution while waiting for the development of wg-dynamic :

#Install :

opkg update && opkg install openssh-client openssh-keygen

#Create the RSA key :

ssh-keygen -t rsa -b 4096 #do not put a passphrase for the key, left empty

#Transfer the public key :

cat ~/.ssh/id_rsa.pub | ssh root@serverIP "cat - >> ~/.ssh/authorized_keys"

#Test the connection :

ssh -i ~/.ssh/id_rsa root@serverIP

#Configure an alias for this connection, to create this file :

nano ~/.ssh/config

#Add :

Host wgssh   # what you want, I use wgssh for the example
    HostName  serverIP
    User root
    IdentityFile ~/.ssh/id_rsa
    Port 22

#Test the connection :

ssh wgssh

#The command to restart the wireguard interface server from openwrt :

ssh -t wgssh 'systemctl restart wg-quick@wg0.service ; /bin/bash' & exit

#I chose cron to run the command every time I start openwrt, another possible solution:

export VISUAL=nano; crontab -e

#Add :

@reboot ssh -t wgssh 'systemctl restart wg-quick@wg0.service ; /bin/bash' & exit

#Or in Luci in Local Startup add the line before exit 0

#Important : wireguard must be started with systemd on the server, if not:

wg-quick down wg0
systemctl start wg-quick@wg0.service

If you have any suggestions to improve the trick or better solution to propose, please leave a comment.

there is a wireguard watchdog already for your situation that come with the "wireguard-tools"

if the watchdog does not fit your setup
another way is, if you own a public dns server, make use of some script to update your public ip address, you will have max 10-15 minutes downtime but works well.

use the domain name instead of the IP address in your wireguard setup, your router will do the rest when the ip change


For usage, see the commit message here. It should help with your problem.

It would be nice, but that's currently not a solution. WireGuard (currently) only resolves hostnames once. The watchdog script solves exactly that issue.


I had tested this script, but it didn't work, is there anything specific to configure or just add it to the cron?

Are you talking about ddns like no-ip? If so, I was looking for a solution without going through a third party.

Also tested, it didn't solve anything for my problem.

Thank all for the feedback.

not no-ip but namecheap/godaddy and the like.

may be this old thread might be of help to you

have the script query something like https://whatismyipaddress.com (lot more you can query) and updates what needed in your/and the other end config

1 Like