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)
Select the Start button, then type settings. Select Settings > Network & internet. The status of your network connection will appear at the top.
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.
Log into a terminal session. Type the command "ping 64.233. 169.104" (without quotation marks) to test the connection.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With