Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Ovid (2709)

Ovid
  (email not shown publicly)
http://publius-ovidius.livejournal.com/
AOL IM: ovidperl (Add Buddy, Send Message)

Stuff with the Perl Foundation. A couple of patches in the Perl core. A few CPAN modules. That about sums it up.

Journal of Ovid (2709)

Tuesday August 12, 2008
08:59 AM

Our 'net connection is soooo bad that I wrote this

[ #37164 ]

At the hotel, our 'net connection goes up and down constantly. Rather than keep switching over to a terminal to ping something, I wanted to be alerted whenever the 'net was back. Searching for tools for OS X to do this for me was problematic because, well, the 'net kept going down. Now I get Growl alerts.

#!/usr/bin/perl

use strict;
use warnings;

use Mac::Growl ':all';
use Net::Ping;
use Getopt::Long;

# set up options
my ( $sleep, $sticky ) = ( 60, 1 );
GetOptions(
    "sleep=i" => \$sleep,     # number of seconds
    "sticky!" => \$sticky,    # sticky growl notifications?
);

# set up MacGrowl
RegisterNotifications( $0, [qw/ping/], [qw/ping/], );
my ($image) = grep { -e } (
    '/Applications/Utilities/Installer.app/Contents/Resources/Caut.tiff',
'/Applica tions/Utilities/Installer.app/Contents/Plugins/TargetSelect.bundle/Contents/Reso urces/Caut.tiff'
);

# set up ping
my $host = shift || 'www.google.com';
my $p = Net::Ping->new( "tcp", 3 );
$p->{port_num} = ( getservbyname( "http", "tcp" ) || 80 );

# do that first ping
my $HOST_LAST_STATUS = !!( $p->ping($host) );
show_status( $host, $HOST_LAST_STATUS, $sticky, $image );

while (1) {
    my $host_status = !!( $p->ping($host) );
    if ( !$host_status ) {
        $host_status = retry( $p, $host );
    }

    if ( $host_status ne $HOST_LAST_STATUS ) {
        show_status( $host, $host_status, $sticky, $image );
    }
    $HOST_LAST_STATUS = $host_status;
    sleep $sleep;
}

sub retry {

    # because it might just be a flaky, intermittant connection
    my ( $p, $host ) = @_;
    for ( 1 .. 3 ) {
        if ( $p->ping($host) ) {
            return 1;
        }
    }
    return '';
}

END { $p->close() }

sub show_status {
    my ( $host, $status, $sticky, $image ) = @_;
    $status = $status ? 'up' : 'down';
    PostNotification(
        $0,
        'ping',
        "$host status",
        "$host is $status",
        $sticky,
        -1,
        $image
    );
}

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.