Re: [SLUG] script to parse and compare an IP address

From: Dylan Hardison (
Date: Sat Apr 01 2006 - 16:04:04 EST

On 4/1/06, Sick Twist <> wrote:
p> I am trying to write a script that parses an unknown IP address from a page
> of HTML, compares the IP address to a file and overwrites the file if the
> saved IP address is different. My question is, what language should I
> investigate to accomplish this? Is this able to be done with a bash script
> and command line utilities or is there another language like perl or python
> that would be better suited for this task? C has always been my game so I'm
> less familiar with the strengths and capabilities of some of the other tools
> out there. Thanks in advance!

I'd use perl.
The following is completely untested, but it should work.
And no, this isn't my april fools. :)

It requires LWP::Simple, part of the www perl library, which on debian
(and probably ubuntu) is libwww-perl.

use strict;
use warnings;
use LWP::Simple 'get';
use IO::File;

my $url = '';
my $file = 'myipfile';

update_ipfile($file, fetch_old_ip($file), fetch_ip($url));

sub fetch_ip {
        my ($url) = @_;
        my $html = get($url);
        if ($html =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/s) {
                my $ip = $1;
                print "Found IP: $ip\n";
                return $ip;
        } else {
                die "Cannot find ip address on $url\n";

sub fetch_old_ip {
        my ($file) = @_;

        # If $file exists, we open it and read the first line.
        if (-e $file) {
                my $fh = new IO::File($file, 'r') or die "Cannot open $file: $!";
                my $line = $fh->getline;
                chomp $line;
                return $line;
        } else {
                # Return something that cannot be an IP.
                return "(nada)";

sub update_ipfile {
        my ($file, $old_ip, $ip) = @_;
        if ($old_ip ne $ip) {
                print "Changing IP to $ip (was $old_ip)\n";
                my $fh = new IO::File($file, 'w') or die "Cannot open $file for writing: $!";
        } else {
                print "Old IP and new IP are the same ($ip).\n";

This list is provided as an unmoderated internet service by Networked
Knowledge Systems (NKS). Views and opinions expressed in messages
posted are those of the author and do not necessarily reflect the
official policy or position of NKS or any of its employees.

This archive was generated by hypermail 2.1.3 : Fri Aug 01 2014 - 20:27:11 EDT