Send an email when IP address changes

Q I have access to my PC at work using the corporate VPN. For years the IP address of my work PC hasn't changed, but lately it seems that it changes once or twice a week. Is there any simple way that my PC (Kubuntu 7.10) could send me an email reporting the new address when it changes?

A Before you do anything else, check with your employer that this is acceptable to them. Having access to your work network from home is convenient; losing your job over it most certainly is not! I don't know of a specific utility for doing this but it is easy to do with this short script, which you can run via Cron.

#/bin/sh
IPADDRESS=$(/sbin/ifconfig eth0 | sed -n 's/.*inet
addr:\([^ ]*\).*/\1/p')
if [[ "${IPADDRESS}" != $(cat ~/.current_ip) ]]
then
echo "Your new IP address is ${IPADDRESS}" |
mail -s "IP address change" you@your.mail
echo ${IPADDRESS} >|~/.current_ip
fi

The real business is done in the second line, which uses a regular expression to extract the current IP address from the output of ifconfig. This is compared with the address stored on a previous run; we use ~/.current_ip to store the address here, but any location that is writable by you and unlikely to be touched by anyone else will do. If the address is different, it sends you an email using the mail command and writes the new address into .current_ip. The mail command is the standard program for sending emails from the command line or scripts, but it does require that you have a local SMTP installed. If mail and its dependencies are not already installed on your computer, it will be easier to use SendEmail, installable from Synaptic. This can use any SMTP server. Replace the mail command above with

sendEmail -s smtp.work.com -f you@work.com -t
you@home.co.uk -u "IP address change" -q

The first argument is the address of the mail server at work (you can remove the -q (quiet) option for testing).

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar