Michael C.
Michael C.

Reputation: 1457

Domain name to IPv6 address in Perl

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 = ???

Upvotes: 1

Views: 2429

Answers (2)

Hamster
Hamster

Reputation: 680

Net::DNS can also help you:

#!/usr/bin/perl -w                                                                                                  
use strict;
use warnings;

use Net::DNS;

my $res   = Net::DNS::Resolver->new;
my $query = $res->query("ipv6.google.com", "AAAA")
    or die "query failed: ", $res->errorstring;

foreach my $rr (grep { $_->type eq 'AAAA' } $query->answer) {
    print $rr->address, "\n";
}

Outputs:

2607:f8b0:4010:801:0:0:0:1005

Upvotes: -1

ysth
ysth

Reputation: 98398

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.

Upvotes: 3

Related Questions