I have the following Perl code to translate domain name to IP address. It works fine in IPv4.
$host = "example.com";
$ip_address = join('.', unpack('C4',(gethostbyname($host))[4]));
However, it does not work if it is an IPv6 only domain name such as "ipv6.google.com".
How can I get one line of code (prefer CORE library) to get IPv6 IP address?
$host = "ipv6.google.com";
$ip_address = ???
In 5.14 and above, you can use the core Socket
:
use 5.014;
use warnings;
use Socket ();
# protocol and family are optional and restrict the addresses returned
my ( $err, @addrs ) = Socket::getaddrinfo( $ARGV[0], 0, { 'protocol' => Socket::IPPROTO_TCP, 'family' => Socket::AF_INET6 } );
die $err if $err;
for my $addr (@addrs) {
my ( $err, $host ) = Socket::getnameinfo( $addr->{addr}, Socket::NI_NUMERICHOST );
if ($err) { warn $err; next }
say $host;
}
For earlier perls, the same functions are available from Socket::GetAddrInfo
on CPAN.