Debian Codegraph @

lemonldap-ng-common/lib/Lemonldap/NG/Common/IPv6.pm

raw
1 package Lemonldap::NG::Common::IPv6;
2
3 use strict;
4 use base 'Exporter';
5
6 our $VERSION = '2.0.10';
7 our @EXPORT = qw(&isIPv6 &net6 &expand6);
8
9 sub isIPv6 {
10 my ($ip) = @_;
11 return $ip =~ /^[a-z0-9:]+$/i;
12 }
13
14 sub net6 {
15 my ( $ip, $bits ) = @_;
16
17 # Convert to binary
18 my $b = join '',
19 map { unpack( 'B*', pack( 'H*', $_ ) ) } split( ':', expand6($ip) );
20 my $net = substr $b, 0, $bits;
21 $net .= '0' x ( 128 - length($net) );
22 $net = unpack( 'H*', pack( 'B*', $net ) );
23 $net = join( ':', ( unpack "a4" x 8, $net ) );
24 $net = compact6($net);
25 return $net;
26 }
27
28 sub expand6 {
29 my @arr;
30 my @_parts = ( $_[0] =~ /([0-9A-Fa-f]+)/g );
31 my $nparts = scalar @_parts;
32 if ( $nparts != 8 ) {
33 for ( my $i = 1 ; $i <= ( 8 - $nparts ) ; $i++ ) {
34 push @arr, hex "0000";
35 }
36 }
37
38 my @parts = map { ( $_ eq '::' ) ? @arr : hex $_ }
39 ( $_[0] =~ /((?:[0-9A-Fa-f]+)|(?:::))/g );
40
41 return join( ":", map { sprintf "%04x", $_ } @parts );
42
43 }
44
45 sub compact6 {
46 $_[0] =~ s/(^|:)0+([\w])/$1$2/g;
47 if ( $_[0] =~ ':0:' ) {
48 my @t = ( $_[0] =~ /\:(?:0\:)+/g );
49 my $ind = -1;
50 my $len = 0;
51 for ( my $i = 0 ; $i < @t ; $i++ ) {
52 $ind = $i if ( length( $t[$i] ) > $len );
53 }
54 $_[0] =~ s/$t[$ind]/::/;
55 $_[0] =~ s/^0//;
56 }
57 return $_[0];
58 }
59
60 1;