关于gethostbyname(perl)
($name,$aliases,$addrtype,$length,@addrs) = gethost*
For the *gethost*()* functions,the @addrs value returned by a successful
call is a list of the raw addresses returned by the
corresponding system library call. In the Internet domain, each
address is four bytes long and you can unpack it by saying
something like:
($a,$b,$c,$d) = unpack('W4',$addr[0]);
The Socket library makes this slightly easier:
use Socket;
$iaddr = inet_aton("127.1"); # or whatever address
$name = gethostbyaddr($iaddr, AF_INET);
# or going the other way
$straddr = inet_ntoa($iaddr);
In the opposite way, to resolve a hostname to the IP address you
can write this:
use Socket;
$packed_ip = gethostbyname("www.perl.org");
if (defined $packed_ip) {
$ip_address = inet_ntoa($packed_ip);
}
以上的英文是标准文档中的解释,笔者下面通过实验具体的解释:
源代码
use Socket;
my @packed_ip;
my $packed_ip1;
my ($a,$b,$c,$d);
my ($d1,$d2,$d3,$d4);
($d1,$d2,$d3,$d4,@packed_ip) = gethostbyname("www.zaobao.com");
$packed_ip1 = inet_aton("www.zaobao.com");
print "====gethostbyname====/n";
foreach my $ip (@packed_ip){
($a,$b,$c,$d) = unpack('W4',$ip);
print "${a}.${b}.${c}.${d}/n";
print inet_ntoa($ip),"/n";
}
print "====inet_aton====/n";
($a,$b,$c,$d) = unpack('W4',$packed_ip1);
print "${a}.${b}.${c}.${d}/n";
print inet_ntoa($packed_ip1),"/n";
结果为:
====gethostbyname====
69.31.112.82
69.31.112.82
69.31.112.131
69.31.112.131
====inet_aton====
69.31.112.82
69.31.112.82
代码解释:
1. gethostbyname通过HOSTNAME(DNS或者IP都可)经过pack压缩处理的IP地址。
@packed_id = gethostbyname(HOSTNAME);
如果HOSTNAME为DNS,则返回的packed_id就是一个list。
如果HOSTNAME为IP,则返回的就是单个值。
2. inet_aton通过HOSTNAME(DNS或者IP都可)经过pack压缩处理的IP地址。
$packed_id = inet_aton(HOSTNAME);
无论HOSTNAME为DNS或者IP返回的是单个值。
3. unpack是将压缩的值还原。上面的英文文档解释说“In the Internet domain, each address is four bytes long”所以,我们如下的使用unpack:
($a,$b,$c,$d) = unpack('W4',$ip);