lunes, 3 de marzo de 2014

Homemade Dynamic DNS Solution

In a lot of countries (Uruguay is one of them), ISPs offer domestic internet services with dynamic ips which change every some hours. In the case of Uruguay, our ISP changes our ip every 12 hours.

This makes makes things difficult for those of us who want to host some service in a computer on our house. For example, lets say that you have a computer with a webserver in your house and you want to access it outside your LAN, over the internet. In order to access the computer at your home you need your public ip (which is the ip that your ISP provides you), but this ip is constantly changing.

The solution is to have a domain pointing to your current ip, and a service that updates your domain dns entries every time your ISP changes your ip.

There are multiple commercial services out there, probably one of the most common one is "dyndns". The problem with these solutions is that they are quite expensive (specially for what they offer) and they dont work 100% of the time.

So, why dont go with the DIY option? This is the path that I took, coding a really basic python script that uses Amazon's Route 53 dns service. What amazon provides its a dns service at a low cost ($0.5 per domain/month) and it gives you an API that allows you to programmatically update the dns entries of your domain.

The basic idea is that every certain amount of time (lets say 5 mins), I do a request to a public webservice that returns my current ip in json format and if the ip changed, it updates my domain's dns entry at Amazon.

This is the python script:

from boto.route53.connection import Route53Connection
import urllib2
import json

# your amazon keys
key = "XXXXXXXXXXXXXXXXXXXXXXX"
access = "XXXXXXXXXXXXXXXXXXXXXXXX"

#Get your current ip 
content = urllib2.urlopen("http://ifconfig.me/all/json").read()
decoded = json.loads(content)
external_ip = decoded['ip_addr']

#Get the current dns entry value from amazon
route53 = Route53Connection(key, access)
zone = route53.get_zone("your-domain.com")
current_dns_ip = zone.get_a("subdomain.your-domain.com.").resource_records[0]

#If your current ip is different than the value that amazon dns service has, update it
if current_dns_ip != external_ip:
        zone.update_a("subdomain.your-domain.com.", external_ip)

(The script uses "boto" which is amazon's official library for python)

Im using it in a Raspberry PI at my home, so I can access to it through ssh over the internet. I set it up as cron to run every 5 mins.

In your crontab file you just need to add (use "crontab -e" for editing your crontab rules):

*/5 * * * * /usr/bin/python /home/pi/dynamicDNS/updateDNS.py

Thats all, with this you will have your "homemade dynamic dns service".





No hay comentarios:

Publicar un comentario