Dynamic DNS—an Object Lesson in Problem Solving

Let's Never Do This Again

It's not that I don't love texting my wife, it's just that hoping someone is home to check an IP address is not the best way to roll your own DNS. There's also the possibility that whatever Dynamic DNS solution I dream up might fail, and I want to make sure I always can figure out my home IP address.

There are a couple different ways I considered for making my IP address always accessible. The simplest was to set up a cron job to upload regularly the results of my PHP script to my Raspberry Pi or to one of my Web hosts. In order to do that, I'd simply have to set up SSH keys so my home server could upload a file without any interactive authentication. This is, in fact, what I recommend. As it happens, however, I'm lazy. What I actually did was set up a cron job that copied my IP address into a text file inside my Dropbox folder. It's not a better solution than scp-ing, but the end result is the same. Here's what my cron job looks like:


1 * * * * /usr/bin/wget -r --quiet -O ~/Dropbox/Public/IP.txt 
 ↪'http://snar.co/ip'

It basically updates my Dropbox folder every hour with my current home IP address. Because Dropbox syncs onto every device and computer I own, it's always readily accessible.

But That's Still Not DNS

Now things get a little complicated. Because I have a full-blown server and a handful of domains to use, it would make sense to set up BIND and serve out a subdomain. BIND does have the ability to change a host entry with a remote update command. It requires setting up encryption keys, and of course, the BIND dæmon has to be configured properly. Remember when I said I was lazy? It's still true. Because all I wanted to do was serve up a single domain name for my home IP address, I opted for something simpler.

DNSMasq is a very simple dæmon that runs on my Linux-based home routers. It handles both DHCP services and DNS resolution. In both cases, the services are very stripped down and simplistic, but if all you need is simple DNS resolution, it doesn't get simpler than DNSMasq. It will look at the server's /etc/hosts file and serve out those entries when queried. All I had to do was get my home IP address into my server's /etc/hosts file, and regularly send DNSMasq the HUP signal to reload its files. A simplistic DNS server was the final piece to the puzzle. Next came implementation.

Putting It All Together

The first step was to create a DNS entry that I could update with DNSMasq. This is simpler than most people realize. I just added an NS record pointing to my Linux server. So basically, I have an entry that looks like this:


home.mydomain.org. IN NS server.mydomain.org.

That means, "when resolving home.mydomain.org, or any subdomain of it, ask server.mydomain.org for the address." This is exactly what I want, because then any time I (or anyone else) tries to access home.mydomain.org, it will ask my server to resolve the name. The only thing left to do is to get my server, which is running DNSMasq, to respond with the proper IP address. That means a couple more cron jobs.

Remember my cool little IP.txt file I keep in my Dropbox? Well, in order to hack together the /etc/hosts file on my server, I had to modify my PHP script a little. In order to create an output compatible with /etc/hosts, I changed it to:


<?php
// Save the IP to a variable
$ip_address = $_SERVER['REMOTE_ADDR'];

// To display the IP:
echo $ip_address;
echo " home.mydomain.org";
?>

Note the space before "home". Now the file in my Public Dropbox folder is a properly formatted /etc/hosts line. In order to combine that with my original hosts file, I created a folder /etc/hosts.d/ on my server, and copied /etc/hosts to /etc/hosts.d/00-original.

Still with me? The last step is to run the following script on the server. I do this script every hour, so if my IP address changes, it should take at the most an hour before it's corrected. Here is the server script:


#!/bin/bash
/usr/bin/wget -r --quiet -O /etc/hosts.d/home 
 ↪'https://dl.dropbox.com/xxx/IP.txt'
cat /etc/hosts.d/* > /etc/hosts
killall -SIGHUP dnsmasq

The first line retrieves the current IP address stored in my Dropbox Public folder. The second line creates a new /etc/hosts file by concatenating all the files in /etc/hosts.d/. Then finally, I send the SIGHUP signal to dnsmasq, so it will reload the /etc/hosts file.

Final Thoughts

The thing I really like about this example as a way to demonstrate problem solving is that there are so many different ways to accomplish the same results. My solution is far from the best. Off the top of my head:

  • I could have the script on my home server check for a change in IP address rather than just constantly updating. If there was a change, it could start the update process on my remote server rather than updating the hosts file every hour whether it needs it or not.

  • Depending on what DNS hosting company you use, it's probably possible to change an address with a remote command. It's also possible there are free DNS servers out there directly supported by a client like ddclient.

  • Because my solution requires a remote Linux server with a static IP, it makes my specific solution inaccessible to many people. That just means you need to think harder in order to dream up a solution!

Where to Go from Here

It seems apropos to make my disclaimer again: the process I just explained is not the most efficient way to solve the problem of changing IP addresses. My methods are crude, my scripts are simplistic, and I haven't included any error correcting whatsoever. (What happens if I can't download the file from Dropbox? Will my script fail? Probably!) The purpose of this article is to make you think. Linux gives us tools that are powerful, flexible and above all else, useful. Sometimes you need to create a little digital duct tape and solve a problem on the fly.

What if you can't seem to come up with a solution to your particular problem? That's where the Linux community really shines. Stop in at the #linuxjournal channel, or attend a local LUG meeting. Folks there are much like me and are eager to help solve problems. Everyone loves a puzzle, and when you get to solve it with Linux? Awesome!

______________________

Shawn Powers is an Associate Editor for Linux Journal. You might find him chatting on the IRC channel, or Twitter

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

No-IP Free Dynamic DNS

Anonymous's picture

Yeah, I understand your frustration with your Free http://www.noip.com No-IP account getting deleted, but don't they have to pay to keep the lights on?

Their http://www.noip.com/free/ free dynamic DNS service has always worked flawless for me, especially since it is a free service. They even give me awesome tech support when I need help.

All I Say Is Worth Share!

GeekSays's picture

You must have burned couple of your hours to compile this tutorial for us, and even-more many of your precious hours in achieving this workaround. I found this is very helpful for me.

Good content, I trust this is

zeennate's picture

Good content, I trust this is a good weblog about Wish to see refreshing content material next time. Thanks for sharing this publish with us. Keep it up. voyance serieuse par mail

This has been wonderfully

ocim's picture

This has been wonderfully open-handed with people like you to present without restraint precisely what many individuals could have marketed as an e book to help make some money for their own end, and in particular since you could have tried it in the event you desired
kata kata motivasi

Sorry from No-IP

No-IP's picture

We apologize that your account was deleted. We do this monthly maintenance to keep our network clean and up to date. We have over 15 million users worldwide, so we like to keep only currently active hostnames on our system... We offer Enhanced Dynamic DNS that is only $14.95 a year and that will disable the 30 day activation... Just a thought.
http://www.noip.com/enhanced/

free dyndns

insider's picture

I personally use free cloudflare DNS services.
Cloudflare also has good API to change params usng POST queries
https://www.cloudflare.com/docs/client-api.html#s5.2

So you can simply edit your A record by issuing curl command every time your IP changes.

I once had a better way I

Anonymous's picture

I once had a better way I wrote a program to check my inbox I have various subject tags

IE

send ip
ping x.x.x.x
trace x.x.x.x

the program would check my email, and if it had various tags as above (I had more) it would execute and send en email response with the outcome. used this while on the road it worked out great :)

Jim

Dynamic DNS

Algot Runeman's picture

Instead of just reporting back the IP to the home server, I added php code to write the ip to a text file at the remote hosted server and then included that into a web page so it was a link. Now I just go to that web page and from there to the home server.

BASH script to log IPs on public web server

Mario Chamorro's picture

As Ralph Loizzo also posted , here is a scriptlet which I call '/bin/whip' . This visits my own public website via an hourly cron job and logs the IPs on all gateway interfaces by visiting non-existent "/ipaddress-IP-iface-IP" like so:

1.2.3.4 - - [22/May/2013:09:59:09 -0400] "GET /ipaddress-home.example.com-eth0-1.2.3.4 HTTP/1.1" 404 1226 "-" "Wget/1.13.4 (linux-gnu)"

It will mail you when the IP changes . I call it 'whip' because I have another alias named 'ship' which SHows IPs on the local machine . 'whip' is the Web How IP . Here's the script:

# ---------

#!/bin/bash
# -
# web / show IP : Mario Chamorro
# -
LOCALSERVER="home.example.com"
REMOTESERVER="www.example.com"
RECIPIENTS="anyone@example.com"
FILEBASE="/tmp/whip";
DEVLIST=`ls /proc/net/dev_snmp6`;
for DEV in $DEVLIST;
do
IP_ADDR=`/sbin/ip addr show dev ${DEV} | grep ${DEV}$ | awk '{ print $2 }' | cut -d/ -f 1`;
RC=$?;
[ -z $IP_ADDR ] || wget -q http://${REMOTESERVER}/ipaddress-${LOCALSERVER}-${DEV}-${IP_ADDR}
# - mail if a new IP address is detected
[ -z $IP_ADDR ] || echo $IP_ADDR >> $FILEBASE.$DEV.txt
[ -r $FILEBASE.$DEV.txt ] && DIFFERENT=$( tail -n 2 $FILEBASE.$DEV.txt | uniq -c | wc -l ) || DIFFERENT=0;
[ $DIFFERENT -eq 2 ] && echo "New Home Gateway IP: $DEV:$IP_ADDR" | mail -s "New Home Gateway IP: $DEV:$IP_ADDR" $RECIPIENTS
done
# ---

DynDNS

Charles Snider's picture

Seriously, DynDNS is the easiest route. Just open a free account (or paid for that matter, it's only a $20 a year), plug your account info into your router, and viola, just a hostname to remember. Automatically updated when your IP changes.

Not free anymore

Chuck's picture

DynDNS doesn't have a free option anymore. If you had a free account with them before you're grandfathered in but they harass you monthly to try to get you to sign up for their paid services.

DynDNS not free-- wrong

GCL's picture

It happens that you're wrong. They do so provide that free account. Yes they do want people to sign up for the paid service, but in actuality all they ask for is that people to sign-in once a month into their account to confirm that it exists.

I've had mine for several years, and that particular issue was not part of the whole issue. All they want is what I've stated.

Nope...

Chuck's picture

...you didn't read my post above. If you signed up years ago for a free account with DynDNS, you were grandfathered in and can continue your free account by logging in to their web site once a month (I do). But if you go to http://dyndns.com today, you will NOT find an option to sign up for free DNS service now -- it doesn't exist.

Reply to comment | Linux Journal

kredit mobil toyota's picture

Terrific article! This is the type of info that are meant to be shared across
the web. Disgrace on Google for not positioning this post higher!
Come on over and seek advice from my site . Thanks =)

All the articles you talked

ibaikal's picture

All the articles you talked about inside post are extremely good and is very helpful. Let me maintain it in mind, thanks for expressing the information retain updating, excited to get more articles.
http://www.ibaikal.com/

myip

markc's picture

If you happen to run your own Bind nameserver on a remote host somewhere then this will work...

https://github.com/markc/shell-scripts/blob/master/doc/myip.md

Keeping track of IP address

Jon TuxTweaks's picture

While I do have a remote web server I could use, I chose to extract my IP from the configuration page on my modem. A cron job checks it every 10 minutes and if it changes then it sends me an email with the new IP.

This may be useful for those without access to a static IP server. You can find my full writeup on my blog : http://tuxtweaks.com/2012/12/keeping-track-of-my-ip-address/

Roll your own dynamic dns

Ralph Loizzo's picture

I have a web site hosted out on the Internet . Every hour my server at home attempts a wget to the remote webserver to a bad filename. My server then checks the error log for the remote ip. If it changes, it changes the DNs entry for my home server. 6 years no problems

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix