Reputation: 107
I've been using the following functions as the basis for a lot of my IP calculation code for years. They require just the built in perl module Socket, so they were very portable.
sub ip2int { return( unpack("N",inet_aton(shift)) ) };
sub int2ip { return( inet_ntoa(pack("N",shift)) ) };
Trying the same thing with Socket6 doesn't seem to be working:
Attempt 1:
$ perl -MSocket6 -e '$x = inet_pton(AF_INET6,"2000::1"); print unpack("q",$x) . "\n"'
32
Attempt 2:
$ perl -MSocket6 -e '$x = inet_pton(AF_INET6,"2000::1"); print
unpack("Q",$x) . "\n"'
32
Attempt 3:
$ perl -MSocket6 -e '$x = inet_pton(AF_INET6,"2000::1"); print unpack("N",$x) . "\n"'
536870912
I can't figure out how to get the integer value of the address so I can use arithmetic for my network related calculations. Anyone have any ideas?
Upvotes: 0
Views: 1219
Reputation: 386561
IPv6 addresses are 128 bits in size.
$ perl -e'
use feature qw( say );
use Socket6 qw( inet_pton AF_INET6 );
say 8*length(inet_pton(AF_INET6, "2000::1"));
'
128
You're very unlikely to have a Perl that supports 128-bit integers. You can enlist the help of Math::Int128
$ perl -e'
use feature qw( say );
use Socket6 qw( inet_pton AF_INET6 );
use Math::Int128 qw( net_to_uint128 );
say net_to_uint128(inet_pton(AF_INET6, "2000::1"));
'
42535295865117307932921825928971026433
Upvotes: 4