# thanks to jdporter and ikegami who have shown me a much better way to do this!
#
# Thanks to ikegami for the code example
use Socket qw( inet_aton inet_ntoa );
sub DottedQuadToLong {
# Accepts triton.littlefish.ca
# Accepts 24.72.30.83
# Accepts 407379539
# etc
return unpack('N', inet_aton(shift));
}
sub LongToDottedQuad {
return inet_ntoa(pack('N', shift));
}
Bad. Very bad. node 221512
Those are needlessly complicated. You're replicating functions inet_aton and inet_ntoa of the core module [mod://Socket]:
use Socket qw( inet_aton inet_ntoa );
sub DottedQuadToLong {
# Accepts triton.littlefish.ca
# Accepts 24.72.30.83
# Accepts 407379539
# etc
return unpack('N', inet_aton(shift));
}
sub LongToDottedQuad {
return inet_ntoa(pack('N', shift));
}
Here are alternatives that only use [doc://pack] and [doc://unpack] (but only accept addresses of the form a.b.c.d):
sub DottedQuadToLong {
return unpack('N', (pack 'C4', split(/\./, shift)));
}
sub LongToDottedQuad {
return join('.', unpack('C4', pack('N', shift)));
}
# for just DottedQuadToLong():
use Net::IP;
print Net::IP->new("24.72.30.83")->intip;
# for both directions:
use Net::IP qw/:PROC/;
print ip_bintoint(ip_iptobin("24.72.30.83",4));
print ip_bintoip(ip_inttobin("407379539",4),4);
sub DottedQuadToLong {
my $ip_str = shift;
return 0 unless $ip_str =~ /^\s*(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\s*$/;
my $ip = 0;
foreach my $quad ($1,$2,$3,$4){
return 0 if ($quad > 255);
$ip = $ip * 256 + $quad;
}
return $ip;
}
perlmonks.org content © perlmonks.org and davidrw, ikegami, jdporter, ruzam
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03