11 Jan 2016 by rayheffer
Curl is one of those command line tools that really does make our lives easier. APIs are expected of everything these days, from your washing machine to cloud management software, and rightly so. This is just a very simple example of using Curl to update a DNS record with an IP address. In this case I use it in my home lab to update a DNS record with my home internet IP address. Unfortunately my ISP doesn’t offer a static IP, but it’s not really a problem. There are free (with limitations) and paid dynamic DNS services out there, but why not do it yourself with a couple of lines of code?
#!/bin/sh # Get external IP address IP=`wget -qO- http://www.rayheffer.com/ip.php`
curl --data-urlencode '&domain=rayheffer.com' --data "&RECORDID=146767" --data "&data="$IP"" https://api.vultr.com/v1/dns/update_record?api_key=<API_KEY>
This script runs in a cron job on my Linux virtual machine, but you could easily use a Raspberry Pi to do the same thing. Every hour, it runs and updates a DNS record which is hosted with a cloud or VPS provider. When I’m travelling and need to remotely access my home lab, I can use the DNS host name.
The first thing the script does is use Wget , which is used to retrieve content from the web, to store the IP address of the remote user in a variable. In this case I have a PHP script (rayheffer.com/ip.php) that reveals the IP address ‘REMOTE_ADDR’ of the client accessing the page. The PHP script contains just one line: and displays the IP in text.
Let me break down the code above for Wget. The -q switch is quiet mode, as I just want the output and none of wget’s additional info. Then O- is used to redirect to stdout. Using Curl and DNS API
Now we have the IP address stores in the IP variable, we can use Curl to interact with your DNS providers API. Most VPS (Virtual Private Server) providers offer a RESTful API with their DNS services. For my personal sites I use Vultr, but many other VPS providers offer the same functionality.
Curl itself is very easy to use, but you do have to understand how it interprets data which we will send to the RESTful API as a POST.
|–data||Sends the specified data to the server in a POST request|
|–data-urlencode||Same as –data, but uses urlencode to send a string that is url encoded so no special characters are sent in our POST|
The API of my VPS provider uses the following functions (full list here):
domain RECORDID data api_key
With these functions we send the IP address to update a DNS A record (e.g. homelab.yourdomain.com)
I run my script on a Linux virtual machine that I have running all of the time, but you could just as easily do this on a Raspberry Pi. Just use crontab to run the script at your preferred interval. If your dynamic IP address doesn’t change that often, then you could just run it every day or every 4-6 hours.
Comments are closed for this post.