in reply to Module for working with IP Addresses and Ranges

It's your choice, but you don't really need a module for this. The simplest way might just be to match the first three numbers, then do a ">= and <=" on the range in the last one.

A slightly more elegant method exploits the fact that IPv4 address are actually 4 byte values -- notice each number ranges from 0-255 (an unsigned, one byte char). If you pack them in order you have a "big endian" (aka. network byte order) number, which is actually how low level networking uses them. Making this easy:

#!/usr/bin/perl -w use strict; sub dot2int { my $address = pop; my @bytes; while ($address =~ /(\d+)/g) { push @bytes,$1 } return unpack('N',pack('C*',@bytes)); } my $first = dot2int('192.168.1.120'); my $last = dot2int('192.168.1.141'); my @testcases = qw( 192.168.1.130 193.168.1.122 255.0.0.27 192.168.1.127 192.168.1.144 192.168.1.139 ); print "$first to $last = ". ($last-$first)." addresses in range\n"; foreach (@testcases) { print $_; my $int = dot2int($_); if ($int >= $first && $int <= $last) { print " spammer!!!\n"; } else { print " OK.\n" } }

The output:

3232235896 to 3232235917 = 21 addresses in range
192.168.1.130 spammer!!!
193.168.1.122 OK.
255.0.0.27 OK.
192.168.1.127 spammer!!!
192.168.1.144 OK.
192.168.1.139 spammer!!!

I would assume there is a module somewhere that includes a function like that, but I can't tell you which one.

Replies are listed 'Best First'.
Re^2: Module for working with IP Addresses and Ranges
by ikegami (Patriarch) on Oct 22, 2010 at 15:25 UTC
    By the way,
    my @bytes; while ($address =~ /(\d+)/g) { push @bytes,$1 }
    can be written as
    my @bytes = $address =~ /(\d+)/g;
    so you end up with
    unpack('N', pack('C*', $address =~ /(\d+)/g))
Re^2: Module for working with IP Addresses and Ranges
by DrHyde (Prior) on Oct 25, 2010 at 09:43 UTC
    It's your choice, but you don't really need a module for this. The simplest way might just be to match the first three numbers, then do a ">= and <=" on the range in the last one.

    While that would work for the example given, it wouldn't work if he needed to see if an address was in the range 192.168.0.0 - 192.168.1.255.

Re^2: Module for working with IP Addresses and Ranges
by ait (Hermit) on Nov 02, 2010 at 18:05 UTC

    Works like a charm, finally wound up using most of your example above. many thanks!

    Alex