如何查找IP地址是否可ping或使用perl?

时间:2012-11-19 11:25:26

标签: perl networking ping

如何找到可ping的IP地址?另外我如何使用perl脚本找到pingable IP是静态的还是动态的?

3 个答案:

答案 0 :(得分:3)

查看Net::Ping模块;

#!/usr/bin/env perl
#
use strict;
use warnings;

use Net::Ping;

my $ip_address = shift || die "Need an IP address (or hostname).\n";

my $p = Net::Ping->new();
if ( $p->ping($ip_address) ) {
    print "Success!\n";
}
else {
    print "Fail!\n";
}

确定IP地址是动态还是静态需要更多的工作。请查看thisthis帖子。

答案 1 :(得分:2)

这样的事情可能有助于检查主机是否响应ICMP:

#!/usr/bin/perl

use strict;
use warnings;
use Net::Ping;

my (@alive_hosts, @dead_hosts);

my $ping = Net::Ping->new;

while (my $host = <DATA>) {
        next if $host =~ /^\s*$/;
        chomp $host;
        if ($ping->ping($host)) {
                push @alive_hosts, $host;
        } else {
                push @dead_hosts, $host;
        }
}

if (@alive_hosts) {
        print "Alive hosts\n" . "-" x 10 . "\n";
        print join ("\n", sort @alive_hosts) . "\n\n"
}

if (@dead_hosts) {
        print "Dead hosts\n" . "-" x 10 . "\n";
        print join ("\n", sort @dead_hosts) . "\n\n";
}

__DATA__
server1
server2
server3

结果如下:

Alive hosts
----------
server1
server2

Dead hosts
----------
server3

我不确定你的第二个要求。

答案 2 :(得分:1)

  

如何找到可ping的IP地址?

[mpenning@tsunami ~]$ perl -e '$retval=system("ping -c 2 172.16.1.1");if ($retval==0) {print "It pings";} else { print "ping failed"; }'
PING 172.16.1.1 (172.16.1.1) 56(84) bytes of data.
64 bytes from 172.16.1.1: icmp_req=1 ttl=255 time=0.384 ms
64 bytes from 172.16.1.1: icmp_req=2 ttl=255 time=0.416 ms

--- 172.16.1.1 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 999ms
rtt min/avg/max/mdev = 0.384/0.400/0.416/0.016 ms
It pings[mpenning@tsunami ~]$

以更友好的形式......

$retval=system("ping -c 2 172.16.1.1");
if ($retval==0) {
    print "It pings\n";
} else {
    print "ping failed\n";
}
  

另外,如何使用perl脚本找到pingable IP是静态的还是动态的?

如果您可以直接访问DHCP服务器,或者您可以嗅探子网并查找DHCP数据包,则只能执行此操作。如果没有更多信息,我们无法回答这个问题。