Perl IPv6 extension / parsing

I have an address like 2001:db8::1 in a scalar and would like to get the extended form 2001:0db8:0000:0000:0000:0000:0000:0001 . The package of the main Perl package - in its vast forest in /usr/lib/perl5/... - a module that will already do this? If not, does anyone have a few lines that would do this?

+4
source share
2 answers

CPAN has a Net::IP that can do what you need.

Here's a transcript showing you this 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 
+9
source

Net::IP is, of course, a great way, because it is easy and powerful. But, if you are going to analyze tons of them, you can use inet_pton from the Socket package instead, since it is 10-20 times faster than the version of the Net::IP object, even with a previously created object. And 4 times faster than 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 an arbitrary machine for me:

 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 
+2
source

Source: https://habr.com/ru/post/1337082/


All Articles