perl - 获取主机名的所有 IP 地址

标签 perl nslookup

我正在尝试获取主机的所有 IP 地址。

这是 nslookup 的输出:

>>nslookup site.com

Server:         8.8.8.8
Address:        8.8.8.8#53

Non-authoritative answer:
Name:   site.com
Address: 1.1.1.1
Name:   site.com
Address: 2.2.2.2

我试过这个代码:
use Socket;
use Data::Dumper;
my $name = "site.com";
@addresses = gethostbyname($name)   or die "Can't resolve $name: $!\n";
@addresses = map { inet_ntoa($_) } @addresses[4 .. $#addresses];
print Dumper(\@addresses);

这是输出:
['1.1.1.1'];

无论如何都要同时获得1.1.1.12.2.2.2 ?

最佳答案

您可以使用 Net::DNS::Resolver获取主机名的 IPv4 地址(A 记录):

use warnings;
use strict;

use feature 'say';

use Net::DNS::Resolver;

my $res = Net::DNS::Resolver->new;

my $name = 'stackoverflow.com';
my $q = $res->query($name);

if ($q){
    print "$name has the following IPv4 addresses:\n";
    for ($q->answer){
        say $_->address if $_->type eq 'A';
    }
}

输出:
stackoverflow.com has the following IPv4 addresses:
151.101.65.69
151.101.193.69
151.101.1.69
151.101.129.69

关于perl - 获取主机名的所有 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52277566/

相关文章:

regex - 如何使用 Perl 从一组字母中生成单词列表?

string - Perl程序从十六进制值打印Unicode

macOS 上的 DNS 问题

go - 为什么golang Lookup*** 函数不能提供服务器参数?

arrays - Perl中 'one dimensional'散列对数组的优势

perl - 将 Moose 与 Test::Class 一起使用 - 构造函数问题

curl - curl 和 nslookup 之间的名称查找差异是什么

powershell - 在 Powershell 中使用 nslookup 获取主机名的 IP 地址

perl - 为什么 "print/regex/? print a : print b"将 "1"放在每行之前?