当前位置: 代码网 > it编程>网页制作>Perl > Perl脚本检测一个域名是否有效

Perl脚本检测一个域名是否有效

2024年05月18日 Perl 我要评论
脚本功能:通过icmp ping或tcp/syn探测指定的域名,探测前检测域名是否有效。file: check.host.pl#!/usr/bin/perluse strict;use net::pi

脚本功能:通过icmp ping或tcp/syn探测指定的域名,探测前检测域名是否有效。

file: check.host.pl

#!/usr/bin/perl

use strict;
use net::ping;
use net::dns;
use time::hires qw();
$| = 1;

my $default_timeout = 2;
my $ping_timeout = 2;
my $dns_timeout = 3;

### 查询域名是否有效
sub querydomain {

  my $domain = shift();
  my $query = '';
  my $dns  = net::dns::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 nothing is failed, other is ok
sub pinghost {
  my $arg = shift();

  return 1 if (ref $arg ne 'hash');

  my $p;
  eval { $p = net::ping->new($arg->{'proto'},$default_timeout,0) };

  if ($@) { 
	warn "err to create net::ping 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, $duration * 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: $0 [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 is down !n";
}

测试例子:

# ./check.host.pl 2013.jb51.net
err: query 2013.jb51.net failed: nxdomain
2013.jb51.net is 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 !

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com