Converting dotted-quad IP addresses to integers
posted 2009-04-18 10:18:18, link to this article
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.
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:
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!
isquared.nl rss (atom)