Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a simple script that verifies periodically (once every few seconds) if there is internet connectivity from that server. To be clear, it's not about to check if an external site/service/server is alive. As reliable internet destinations I use IPs of sites like google, yahoo, etc. Normally I use 3 destinations (LAN, ISP network, outside ISP)

My current code responsible for this is just a simple and dirty call to ping:

    my $pingResponse = `ping -c 1 -w 1 123.123.123.123`;
    my $isConnected = parsePingResponse($pingResponse);

It seems to work, but I'm sure it's not the right/best way to accomplish this task. There are at least 3 drawbacks: external system call, it's slow, it has a relatively long deadline of 1 second.

So, my question is: how to implement simply and efficiently a ping functionality the perlish way in order to verify if the internet connection is alive?

(I think LWP is an overkill. It's not important if a site or a page is available, just if some external IPs are reachable. Probably it should be something simple involving low-level networking)

like image 699
ArtMat Avatar asked Feb 14 '13 12:02

ArtMat


People also ask

How do I check my connection status?

Select the Start button, then type settings. Select Settings > Network & internet. The status of your network connection will appear at the top.

How do you check the reliability of a connection?

Online services such as Pingtest or Speedtest enable you to test the reliability of your device's Internet connection by running various tests. Internet users can experience a variety of problems when connecting to websites or when they are using services on the Internet.

How do I know if Ubuntu is connected to Internet terminal?

Log into a terminal session. Type the command "ping 64.233. 169.104" (without quotation marks) to test the connection.


2 Answers

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.

like image 163
rjh Avatar answered Sep 20 '22 16:09

rjh


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;
    }   
}
like image 22
djaa2807 Avatar answered Sep 19 '22 16:09

djaa2807