Brain Goo

Carpe Crap ‘em

Brain Goo header image 2

 

 

Perl code to find an IP A in subnet B/C

June 5th, 2007 · No Comments

my $ip = '1.2.3.4';
my $block1 = '1.2.3.0/27';

if(checkip($ip, $block1)) {
    print STDOUT "$ip is in $block1\n";
}
else {
    print STDOUT "$ip is not in $block1\n";
}

sub checkip() {
    my $ip = shift;
    my $block = shift;

    @ip1 = split(/\./, $ip);
    $ip1 = $ip1[0] * 2**24 + $ip1[1] * 2**16 + $ip1[2] * 2**8 + $ip1[3];
    my @temp = split(/\//, $block);

    $ip2 = $temp[0];
    my $netmask = $temp[1];

    @ip2 = split(/\./, $ip2);
    $ip2 = $ip2[0] * 2**24 + $ip2[1] * 2**16 + $ip2[2] * 2**8 + $ip2[3];

    if( $ip1 >> (32-$netmask) == $ip2 >> (32-$netmask) ) {
            return 1;
    }
    return 0;
}

Tags: How Tos · Programming · ip addressing · ipv4 · networking · perl

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment