Dealing with Dynamic Ip Address

24/03/2019 19:01 GMT

For dealing with dynamic ip addresses, the most elegant solution I could find, is to place the ip address of the network into a simple file using a shell script and sync the folder across different machine that you trust using file sync software like Syncthing or Relio Sync. Here an example of a script:

#!/bin/bash
cd "$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"
IP=$(dig -4 +short myip.opendns.com @resolver1.opendns.com)
if [ "$IP" != "$(cat IpAddress/Server)" ]; then
        echo $IP > IpAddress/Server
        # Tips: you could do some fancy curl stuff here, e.g. cloudflare API ;)
fi

And setup a cron to run the script about every 15 minutes.

Yes, one could say you can use DynDNS but there is a few disadvantages to that approach, for example, you can’t control where you’re sourcing the IP address from, you’ll end up distributing the IP address globally which may not be desirable and you’re handing over control to a third party.

How would I use the file with SSH, that easy I show you an example.

$ ssh -o 'HostKeyAlias myhost' [email protected]$(cat ~/IpAddress/Server)

It’s really that simple, just make sure you add the alias to ~/.ssh/known_hosts and you’re done 🙂

| |