Converting Dotted-quad IP Addresses to Integers

Some years ago, before I was lazy enough to just grab a module from CPAN, I wrote this handy Perl function to convert a dotted quad IP address to an integer.

1
2
3
4
5
6
7
8
9
sub dotquadToInt($) {
        my ($e, $m, $r) = (24,,);
        my @octet = split(/\./, $_[0]);
        foreach $m (@octet) {
               $r += $m*2**$e;
               $e -= 8;
        };
        return $r;
}

I think the above is pretty, because it is easy to adapt to different bases etc. But it is also needlessly complex, a more elegant way to achieve the same is something like this:

1
2
3
4
sub dotquadToInt($) {
        my @octet = split(/\./, $_[0]);
        return $octet[0]*2**24 + $octet[1]*2**16 + $octet[2]*2**8 + $octet[3];
}

Maybe these functions are of use to someone, though I would recommend everybody to use the excellent Net::IP Perl module instead!

Comments