ElectricWeasel ElectricWeasel - 1 year ago 212
Perl Question

Unpacking an IPv6 address from inet_pton

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"'

Attempt 2:

$ perl -MSocket6 -e '$x = inet_pton(AF_INET6,"2000::1"); print
unpack("Q",$x) . "\n"'

Attempt 3:

$ perl -MSocket6 -e '$x = inet_pton(AF_INET6,"2000::1"); print unpack("N",$x) . "\n"'

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?

Answer Source

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"));

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_int128 );
   say net_to_int128(inet_pton(AF_INET6,"2000::1"));

There doesn't seem to be a Math::UInt128 (even though requesting to install Math::UInt128 installs Math::Int128), so this will actually give a signed number. You'll have to use something "fancier" like Math::BigInt to get an unsigned number.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download