Scripting function: To detect the specified domain name by using ICMP ping or Tcp/syn to detect the validity of the domain name before probing.
file:check.host.pl #!/usr/bin/perl use strict;
Use Net::P ing;
Use Net::D ns;
Use Time::hires qw (); $|
= 1;
My $DEFAULT _timeout = 2;
My $PING _timeout = 2;
My $DNS _timeout = 3;
### query domain name is valid sub Querydomain {my $domain = shift ();
my $query = ';
My $dns = Net::D ns::resolver->new (tcp_timeout => $DNS _timeout, udp_timeout => $DNS _timeout, retry => 1
);
My @nameservers = qw/8.8.8.8 114.114.114.114/;
$dns->nameservers (@nameservers);
eval {$query = $dns->search ($domain, ' A ');
};
if ($@ or! $query) {My $err = $dns->errorstring;
Print "Err:query $domain failed: $errn";
return if ($err =~/nxdomain/);
Return ' OK ';
### return to is FAILED, the other is OK sub Pinghost {My $arg = shift ();
Return 1 if (ref $arg ne ' HASH ');
My $p;
eval {$p = Net::P ing->new ($arg->{' Proto '}, $DEFAULT _timeout,0)};
if ($@) {warn "ERR to create Net::P ing object: $@n";
Return
} $p->hires (); My ($host, $duration, $hip, $rep, $ret);
### Tcp/syn Ping if ($arg->{' proto '} eq "syn") {$p->{port_num} = $arg->{' Port '};
$p->ping ($arg->{' host '}, $PING _timeout); if ($host, $duration, $hip) = $p->ack ()) {printf ("Ack Reply from $arg->{' host '}[%s] time=%.2f msn", $hip, $durati
On * 1000);
$ret = ' OK ';
else {warn "SYN Request for $arg->{' host '} timed OUT.N";
} ### ICMP ping else {($rep, $duration, $hip) = $p->ping ($arg->{' host '}, $PING _timeout);
if ($rep) {printf ("Echo Reply from $arg->{' host '}[%s] time=%.2f msn", $hip, $duration * 1000);
$ret = ' OK ';
else {warn "PING Request for $arg->{' host '} timed OUT.N";
}} $p->close;
Undef ($p);
return $ret;
} My $ARG = {proto => ' syn ', Port => 80};
My $host = $ARGV [0];
My $proto = $ARGV [1];
Die "Usage: $ [icmp]n" if (! $host);
$ARG->{' host '} = $host;
$ARG->{' proto '} = $proto if ($proto);
My $code; if (&querydomain ($host) EQ ' OK ' and $code = &pinghost ($ARG)) {print ' $host is online!n ';} else {print ' $host are down!n;}
Test Example:
#./check.host.pl 2013.jb51.net
err:query 2013.jb51.net failed:nxdomain
2013.jb51.net are down!
#./check.host.pl www.jb51.net
ACK Reply from www.jb51.net[173.255.214.254] time=307.04 Ms
Www.jb51.net is Online!
#./check.host.pl jb51.net ICMP
Echo Reply from jb51.net[173.255.214.254] time=205.61 Ms
jb51.net is online!
#./check.host.pl chinagfw.com ICMP
PING Request for chinagfw.com timed out.
Chinagfw.com is down!