如何使用Perl为DNS查找配置“检查错误”?

时间:2010-09-27 07:01:22

标签: perl dns resolve

我有一个脚本,允许我在输入将转发到DNS服务器的IP地址后查找主机名。

然而,即使一切正常,如果无法找到DNS,程序似乎也无法打印出我想要的错误。

代码:

#!/usr/bin/perl

use IO::Socket;
use warnings;
use strict;
use Term::ANSIColor;
use Socket;
use Sys::Hostname;

print "\nYou are now in Show DNS IP Address!\n\n";

print "*************\n";
print "|DNS Address|\n";
print "*************\n";

print "\nPlease enter a hostname that you wish to view\n\n";
print "\n\nEnter the hostname of Choice Here: ";
my $userchoice =  <>;
chomp ($userchoice);

my $host = hostname();

my $hostname = $userchoice;

my $packed_ip = gethostbyname("$hostname");

my $ip_address = inet_ntoa($packed_ip) or system("clear"), system("/root/Desktop 
/showdns.pl"), die("Can't resolve $hostname: $!\n ,try again");

my $coloredText = colored($name, 'bold underline blue');
print "\n\nThe hostname IP address is: $coloredText\n\n";

print "Press enter to go back to the main menu\n\n";
my $userinput2 = &lt;&gt;;
chomp ($userinput2);

system("clear");
system("/root/Desktop/simpleip.pl");

有人可以就代码提出一些建议吗?

1 个答案:

答案 0 :(得分:1)

不要滥用|运算符来执行一系列操作。虽然你想要的东西对我来说并不清楚,但这并不是你想要的。什么时候应该调用两个系统调用?成功与否?

如果要在调用die()时完成它,你可以这样做:

my $i_addr = scalar(gethostbyname($hostname || 'localhost'))
    or system("clear"), system("/root/Desktop/showdns.pl"), die("Can't resolve $hostname: $!\n ,try again");
my $name = inet_ntoa($i_addr);

my $i_addr = scalar(gethostbyname($hostname || 'localhost'));
if ( $i_addr ) {
    system("clear");
    system("/root/Desktop/showdns.pl");
    die("Can't resolve $hostname: $!\n ,try again");
}
my $name = inet_ntoa($i_addr);

(修正了inet_ntoa的误用;你需要先验证gethostbyname的成功,然后再调用它。)