2012-11-08 23 views
1

我在這裏做錯了什麼,我不知道是什麼。這個小程序應該列出4個IPv4地址,並使用hostent的gethost()來解析域。如果失敗,則保持IPv4格式。失敗與gethost()(使用Net :: hostent)

輸出:

180.76.5.59 has a hostname of 180.76.5.59 
199.200.9.44 has a hostname of 199.200.9.44 

然後,錯誤我收到:

Can't locate object method "137.48.78.181" via package "Net::hostent" at 
    ./rev.pl line 19 (#1) 
(F) You called a method correctly, and it correctly indicated a package 
functioning as a class, but that package doesn't define that particular 
method, nor does any of its base classes. See perlobj. 

Uncaught exception from user code: 
Can't locate object method "137.48.78.181" via package "Net::hostent" at ./rev.pl line 19. 
at ./rev.pl line 17 

17:如果(我的$ H =和getHost($主機))19:$ NAME =($^h - > $名稱());

代碼:

#!/usr/bin/perl 

use Modern::Perl; 

use Net::hostent; 
use diagnostics; 

my @ipaddresses = qw/ 180.76.5.59 199.200.9.44 137.48.78.181 137.48.185.207 /; 
#host 137.48.78.181 
foreach my $host (@ipaddresses) 
{ 
    my $name = $host; 

    # my @sysArg = ("host", $host); 
    # system(@sysArg); 

if (my $h = gethost($host)) 
{ 
    $name = ($h->$name()); 
} 
    print "$host has a hostname of $name\n"; 
} 

你會發現我已經註釋掉系統主機命令,當我使用它工作正常,但我沒有想到的方式來捕捉域(和沉默輸出)。 任何幫助非常感謝。

使用系統時(@sysArg);我得到這個:

Host 59.5.76.180.in-addr.arpa not found: 2(SERVFAIL) 
Host 44.9.200.199.in-addr.arpa. not found: 3(NXDOMAIN) 
181.78.48.137.in-addr.arpa domain name pointer pc-78-181.hpr.unomaha.edu. 
207.185.48.137.in-addr.arpa domain name pointer pki174b-01.ist.unomaha.edu. 
+0

Shoulnd''t使用'gethostbyaddr'? – ikegami

回答

1

您有錯誤的$印記。

此代碼:

$name = ($h->$name()); # WRONG 

...應該是:

$name = ($h->name()); 

Can't locate object method "137.48.78.181"了這層含義:的$name字符串值被用作方法名。

+0

謝謝,我是一個白癡,因爲我預料〜! –

+0

是的,但不會將地址轉換爲名稱。您仍然需要將'gethost'切換到'gethostbyaddr'。這只是答案的一半。其餘的請看我的。那麼,還有這一半。 – ikegami

3

反向查找使用gethostbyaddr完成。

use Net::hostnet qw(gethostbyaddr); 
use Socket  qw(inet_aton); 

my $h = gethostbyaddr(inet_aton($ip))); 
say $h->name; # Not $h->$name