oded_dd has asked for the wisdom of the Perl Monks concerning the following question:

hi, I'm beginner i am trying to write a script that pings a group of ip addresses from a file and returns if it alive or not and i dont want how to start... Thank you!

20050317 Edit by castaway: Changed title from 'ping'

Replies are listed 'Best First'.
Re: Pinging multiple hosts
by sh1tn (Priest) on Mar 13, 2005 at 13:00 UTC
    You may want to see Net::Ping.
    use Net::Ping; $host = shift; $p = Net::Ping->new(); $p{"timeout"} = 0.05; # or whatever print "$host is alive.\n" if $p->ping($host); $p->close();
    Update:
    # $p{"timeout"} is wrong # $p->{"timeout"} is correct


Re: Pinging multiple hosts
by borisz (Canon) on Mar 13, 2005 at 13:11 UTC
    perl script.pl < my_list_of_ips.txt
    #!/usr/bin/perl use Net::Ping; my ( @ips, @up ); $" = "\n"; while(<>) { chomp; push @ips, $_ if /^(\d{1,3}\.){3}\d{1,3}$/; } print @ips; my $p = Net::Ping->new( "syn", 5 ); $p->{port_num} = 7; $p->ping($_) for (@ips); while ( my ( $host, $rtt, $ip ) = $p->ack ) { push @up, $ip; } print @up;
    Boris
Re: Pinging multiple hosts
by CountZero (Bishop) on Mar 13, 2005 at 13:22 UTC
    Or if you are on a Windows-box:
    use strict; use Win32::PingICMP; my $p = Win32::PingICMP->new(); foreach (qw /www.yahoo.com www.cpan.org www.perlmonks.org/) { if ($p->ping($_)) { print "Pinging to $_ took ".$p->details->{roundtriptime}."\n"; } else { print "Pinging $_ unsuccessful: ".$p->details->{status}."\n"; } }

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

Re: Pinging multiple hosts
by gam3 (Curate) on Mar 13, 2005 at 18:03 UTC
    If you have fping you can use this.
    our @hosts = qw /www.yahoo.com www.cpan.org www.perlmonks.org bob.net/; our %host_state = (); #our @alive = `fping -a @hosts`; # 2>/dev/null keeps us from get error messages for fping our @alive = `fping -a @hosts 2> /dev/null`; chomp @alive; for my $host (@alive) { $host_state{$host} = 1; } for my $host (@hosts) { print $host, " is "; print $host_state{$host} ? "alive" : "dead"; print "\n"; }
    A picture is worth a thousand words, but takes 200K.
Re: Pinging multiple hosts
by blazar (Canon) on Mar 14, 2005 at 10:10 UTC
    While I think that using a dedicated module, as duly pointed out by others, is the best solution, if you run an external ping utility you may gain something in terms of efficiency by parallelizing.

    Minimal example code from an old script (assuming *NIX/Linux here):

    #!/usr/bin/perl -l use strict; use warnings; die "Usage: $0 <net>\n" unless @ARGV == 1; # Rudimentary check on the argument (my $net=shift) =~ s/\.0+$/./ or die "Supply an IP of the form <#.#.#.0>\n"; print "Begun pings at " . localtime; my @p; open $p[$_], "-|", "ping $net$_ -c 10" or die "Couldn't start ping for $net$_: $!\n" for 1..255; shift @p; undef $/; print map <$_>, @p; __END__