Using Bind9 with Dynamic IP - Last update 23rd August 2017

The problem is that you run your own DNS server and you have a dynamic IP.

Every time there is an interruption in service, for whatever reason, your ip address changes and nothing works.

There are probably several ways of updating your ip using nspdate but they all seemed too hard to me, so I wrote a script to do this task.

Here is the script which I made into a file called "":

old=`cat oldip.txt`
if expr "$ip" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' >/dev/null; then
  for i in 1 2 3 4; do
    if [ $(echo "$ip" | cut -d. -f$i) -gt 255 ]; then
      echo "fail ($ip)"
      exit 1
    echo "success ($ip)"
  echo "fail ($ip)"
  ip=`cat oldip.txt`
  exit 1
if [ $ip != $old ]
  echo "Old " $old "new" $ip
  sed -i "s/$old/$ip/g" "/etc/bind/zones/"
  service bind9 restart
  echo $ip > oldip.txt
  mail -s "AUTO DNS Change" < /dev/null
  echo "No Change"
  echo "NC Old " $old "NC new" $ip


How this works!

Line 2: The old ip address is read into variable $old from a file called "oldip.txt"
Line 3: The current IP is read into $ip from a curl statement
Lines 4-10: Test if curl is returning an ip address not an error
Line 11: All good valid IP
Line 12: else (we have a bad ip)
Line 13: tell us we have a bad IP
Line 14: We have a bad IP address so make the new IP address the same as the old IP address and nothing will happen.
Line 17: If $ip and $old do not match then we need to do some work.
Line 20: Use sed (stream editor) to search the zone file for all instances of the old ip and replace with new ip
Line 21: Restart bind/zones/example
Line 22: Replace the old ip address in oldip.txt with the new one. (So we are ready to go again.)
Line 23: Send me an email to tell me that my ip address has changed.
Line 24: Else if $ip does equal $old then there is nothing to do.
Line 25-26: Tell me "no change"
Line 27: End of if statement

In order to run this automatically every 60 minutes I added the following cron command:

*/60 * * * * echo rootpassword | sudo -S /home/example/

Other things to know

1. It is considered bad practice to hard code the root passwords in crontab (it's my server and I do not care).

2. I created a file called "oldip.txt" and put my current ip address in it to start (once only).

If you have any questions you can mail me: chris at the domain you are now on.