下面的Perl代码可以将域名转换为IP地址。它在IPv4中运行得很好。
$host = "example.com";
$ip_address = join('.', unpack('C4',(gethostbyname($host))[4]));但是,如果它只是一个IPv6域名,比如"ipv6.google.com“,它就不能工作。
如何获得一行代码(更喜欢核心库)来获取IPv6 IP地址?
$host = "ipv6.google.com";
$ip_address = ???发布于 2014-07-04 13:57:18
在5.14及以上版本中,您可以使用核心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;
}对于早期的perls,同样的函数可以从CPAN上的Socket::GetAddrInfo中获得。
发布于 2014-07-04 13:19:10
Net::DNS还可以帮助您:
#!/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";
}产出:
2607:f8b0:4010:801:0:0:0:1005https://stackoverflow.com/questions/24574821
复制相似问题