从字符串中提取 IP 地址

从字符串中提取 IP 地址

Linuxhost命令返回:

hostA.domain.com has address xx.xxx.xxx.xx

如何获取 IP 地址并将其放入$ipaddr变量中?

open(FILE, "hostlist.txt") or die("Unable to open file");
@hostnames = <FILE>;
close(FILE);
foreach $hostname (@hostnames)
{
    $lookup = qx(host $hostname);
    $ipaddr = grep ip_address $lookup;  <---- need help here
    print $ipaddr;
}

答案1

既然您将其发布在 Unix & Linux 网站上,而不是 StackOverflow 上,我想知道这样的内容是否不是您正在寻找的内容:

cat hostlist.txt | xargs resolveip -s

不过,这只会返回一个 IP 地址。

某些主机名将有多个与其关联的 IP 地址:

$ host www.google.com
www.google.com is an alias for www.l.google.com.
www.l.google.com has address 74.125.227.18
www.l.google.com has address 74.125.227.17
www.l.google.com has address 74.125.227.16
www.l.google.com has address 74.125.227.20
www.l.google.com has address 74.125.227.19

要仅获取 IP 列表,一种方法是:

host <hostname> | grep "has address" | awk '{print $4}'

如果您想坚持使用 Perl,请使用resolveip:

$ipaddr = qx(resolveip -s $hostname);

或者获取所有 IP,而不执行任何 shell 命令:

use Socket;
@ipaddrs = map { inet_ntoa($_) } (gethostbyname($hostname))[4,];

答案2

为什么不直接使用呢dig +short

答案3

我会用类似的东西:

(\d{1,3}\.){3}\d{1,3}

如果您想要更严格的东西,那么您可能会:

([012]?\d{1,2}\.){3}[012]?\d{1,2}

但即便如此,仍然有些松动。例如,它仍然允许“269.278.287.296”错误匹配。

但两者都符合标准 0.0.0.0 到 255.255.255.255。

答案4

要添加到 @mkopala 的答案,如果您有多个主机并且想要跟踪它们,请构建一个散列,以便可以轻松引用主机到 ip 映射。

例子:

#!/usr/bin/perl
use Socket;
@hostnames = ('www.google.com', 'www.yahoo.com', 'www.facebook.com');
%ipaddrs = ();
foreach $hostname (@hostnames) {
        map { $ipaddrs{$hostname} = inet_ntoa($_) } (gethostbyname($hostname))[4,];
}

相关内容