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)
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.