I have an address like 2001:db8::1
in a scalar, and would like to get the expanded form, 2001:0db8:0000:0000:0000:0000:0000:0001
. Does the main Perl package ship - in its vast forest in /usr/lib/perl5/...
- a module that will already do this? If not, does someone have a few lines that would do this?
CPAN has Net::IP
which can do what you need.
Here's a transcript showing you it in action:
$ cat qq.pl
use Net::IP;
$ip = new Net::IP ('2001:db8::1');
print $ip->ip() . "\n";
$ perl qq.pl
2001:0db8:0000:0000:0000:0000:0000:0001
Net::IP
is definitely a great way to go, because it's easy and powerful. But, if you're going to parse tons of them you might consider using inet_pton
from the Socket
package instead, as it's 10-20 times faster than the Net::IP
object version, even with the object pre-created. And 4ish times faster than the ip_expand_address
version:
use Net::IP;
use Time::HiRes qw(gettimeofday tv_interval);
use Socket qw(inet_pton AF_INET6);
use bignum;
use strict;
# bootstrap
my $addr = "2001:db8::1";
my $maxcount = 10000;
my $ip = new Net::IP($addr);
my ($t0, $t1);
my $res;
# test Net::IP
$t0 = [gettimeofday()];
for (my $i = 0; $i < $maxcount; $i++) {
$ip->set($addr);
$res = $ip->ip();
}
print "Net::IP elapsed: " . tv_interval($t0) . "\n";
print "Net::IP Result: $res\n";
# test non-object version
$t0 = [gettimeofday()];
for (my $i = 0; $i < $maxcount; $i++) {
$res = Net::IP::ip_expand_address('2001:db8::1', 6);
}
print "ip_expand elapsed: " . tv_interval($t0) . "\n";
print "ip_expand Result: $res\n";
# test inet_pton
$t0 = [gettimeofday()];
for (my $i = 0; $i < $maxcount; $i++) {
$res = join(":", unpack("H4H4H4H4H4H4H4H4",inet_pton(AF_INET6, $addr)));
}
print "inet_pton elapsed: " . tv_interval($t0) . "\n";
print "inet_pton result: " . $res . "\n";
Running this on a random machine for me produced:
Net::IP elapsed: 2.059268
Net::IP Result: 2001:0db8:0000:0000:0000:0000:0000:0001
ip_expand elapsed: 0.482405
ip_expand Result: 2001:0db8:0000:0000:0000:0000:0000:0001
inet_pton elapsed: 0.132578
inet_pton result: 2001:0db8:0000:0000:0000:0000:0000:0001
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With