Tracking Dynamic IP

So it is nice to be able to remotely connect to your home computer. Many (included my) ISPs, give dynamic IP addresses, and although these don’t change often, they do change and are a pain to remember anyway. My solution is to have my computer e-mail me whenever it discovers it has a new IP address! You can easily configure exim4 to send emails from a linux machine through gmail, a great guide is here.

Once you have that you just need a little script, mine does this with python by asking http://icanhazip.com. and writing a temporary file with the old ip in /var/tmp. It only sends you a message when the IP changes, no need to spam your email box!

 

#!/usr/bin/python

''' A super simple script to email changes in a dynamic IP to
an email address. If you drop this in /etc/cron.* , it will periodically
poll a website to check if your iP has changed, and if it has it well
send you an e-mail with the new one!

Alex Knaust - 2/28/2013
'''

import os, smtplib, urllib2, re
from email.mime.text import MIMEText

# file to save the last IP address in
IPLOC = '/var/tmp/ip'

# site from which to get IP, if you change this you might need to alter get_live_ip
IPSITE = 'http://icanhazip.com'

# Message to send yourself with the IP
MAILSTR = '''Hi, My new IP address is {0}\n'''

# Address from which the email is being sent (this should probably match your SMTP setup
FROMADDR = 'you@host.com'

# Address to which to send the message
TOADDR = 'you@host.com'


#####################################################
############### CODE ################################
#####################################################
def save_ip(ipstr):
    '''Save the Ip to IPLOC, return true if successful, false otherwise'''
    try:
        with open(IPLOC, 'w') as f:
            f.write(ipstr)
    except:
        return False
    return True
    
def get_old_ip():
    '''Gets the old IP by reading IPLOC, returns None if it could not be read'''
    try:
        with open(IPLOC, 'r') as f:
            ip = f.read()
        return ip.strip()
    except IOError:
        return None
    
def get_live_ip():
    '''Return the IP address of this computer by polling IPSITE
    
    returns None if not successful
    '''
    try:
        f = urllib2.urlopen(IPSITE)
        return f.read().strip()
    except urllib2.URLError:
        return None

def send_mail(ipstr):
    '''Tries to send an email about the change of IP to the TOADDR
    
    returns true if successful, false otherwise
    '''
    msg = MIMEText(MAILSTR.format(ipstr))
    msg['Subject'] = 'IP Address change'
    msg['From'] = FROMADDR
    msg['To'] = TOADDR
    
    try:
        s = smtplib.SMTP('localhost')
        s.sendmail(FROMADDR, [TOADDR, ], msg.as_string())
        s.quit()
    except:
        return False
    return True

def main():
    oldip = get_old_ip()
    newip = get_live_ip()
    
    if newip is not None:
        if oldip is not None:
            if newip != oldip:
                send_mail(newip)
                save_ip(newip)
        else:
            send_mail(newip)
            save_ip(newip)

if __name__ == '__main__':
    main()

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>