Domain name to IPv6 address in Perl

匿名 (未验证) 提交于 2019-12-03 10:10:24

问题:

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

回答1:

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.



回答2:

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!