How to check the presence of the internet connection in Perl?

The perlish way to do this would be Net::Ping.

my $p = Net::Ping->new;
if ($p->ping("123.123.123.123", 1)) {
    print "Host is reachable\n";
}

The timeout may be a float (e.g. 0.5) if you want the command to run faster. You'll need to choose a timeout that fits your needs; a higher timeout is more likely to be correct about the internet connectivity, but will take longer.


The example given by rjh above does not work in many cases because he did not initialize the constructor properly. This example below might help:

use Net::Ping;

my $p = Net::Ping->new("icmp");
while(1){
printf "Checking for internet\n";
    if ($p->ping("www.google.com")){
    printf "Internet connection is active!\n";
        sleep 1;
    last; #break out of while loop if connection found
    }
    else{
    printf "Internet connection not active! Sleeping..\n";
        sleep 60*60;
    }   
}