A Perl script to check for IP address changes

Oct 27, '04 09:36:00AM

Contributed by: oeholmen

I use one of my Macs to run a webserver, but my ISP does not support static IP addresses. So my IP address changes sometimes, causing some of my websites to become unavailable until I can update the IP address. With services like dyndns.org, you can do this automatically, but not all services support automatic updates. So I wrote a Perl script to have me notified by email whenever my IP changes. This way, I can minimize the time my sites are offline.

In addition to the script, you need a file that contains your current IP address and you need to add a cron job to run the script as often as you like (it also uses sendmail to send the message). I use checkip.dyndns.org to check the IP address. There might be an easyer way to obtain the WAN address, and suggestions are welcome!

Here is the script:

#!/usr/bin/perl -w

use strict;

my $mailprog = '/usr/sbin/sendmail';
my $ip_last_check_file = "/Path/To/Current/IP/Address";
my $ip_now = `curl -s http://checkip.dyndns.org`;
$ip_now =~ s/.*?(\d+\.\d+\.\d+\.\d+).*/$1/s;

open(IP, "<$ip_last_check_file") or die "Cannot open $ip_last_check_file: $!";
my $ip_last_check = <IP>;
close(IP);

if ($ip_now ne $ip_last_check)
{
  open(IP, ">$ip_last_check_file") or die "Cannot open $ip_last_check: $!";
  print IP $ip_now;
  close(IP);

  open (MAIL, "|$mailprog -t") || die "Can't open $mailprog!\n";
  print MAIL "From: user\@domain.com\n";
  print MAIL "To: user\@domain.com\n";
  print MAIL "Subject: Your IP-address has changed\n";
  print MAIL "Your IP-address has changed to $ip_now\n";
  close MAIL;
}

exit;
Make sure you remember to make the script executable (chmod +x script_name).

[robg adds: A couple of previous hints explain how to do similar things via AppleScript and by using an intermediate server to redirect to the current IP address. As noted, dyndns.org can also do this automatically...]

Comments (11)


Mac OS X Hints
http://hints.macworld.com/article.php?story=2004102508055243