关于gethostbyname(perl)

关于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通过HOSTNAMEDNS或者IP都可)经过pack压缩处理的IP地址。

 

  @packed_id = gethostbyname(HOSTNAME);

 

如果HOSTNAMEDNS,则返回的packed_id就是一个list

如果HOSTNAMEIP,则返回的就是单个值。

2.       inet_aton通过HOSTNAMEDNS或者IP都可)经过pack压缩处理的IP地址。

 

                           $packed_id = inet_aton(HOSTNAME);

 

无论HOSTNAMEDNS或者IP返回的是单个值。

3.       unpack是将压缩的值还原。上面的英文文档解释说“In the Internet domain, each address is four bytes long”所以,我们如下的使用unpack

 

              ($a,$b,$c,$d) = unpack('W4',$ip);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值