透過hostname獲取IP的perl指令碼

shiri512003發表於2010-04-21

作者: 絃樂之花 | 可以轉載, 但必須以超連結形式標明文章原始出處和作者資訊及版權宣告

連結http://shiri512003.itpub.net/post/37713/499431

[@more@]

有時候我們會需要獲取主機IP資訊,下面收錄一個透過主機名獲取IP的perl指令碼

#!/usr/bin/perl
# resolv.pl written by detour@metalshell.com
#
# Resolves an ip into a host or a host into an ip.
#
# 
#
 
use Socket;
use strict;
 
my $host_name = hostname($ARGV[0]);
print "$ARGV[0] resolves to $host_namen";
 
sub hostname {
 
  my (@bytes, @octets,
    $packedaddr,
    $raw_addr,
    $host_name,
    $ip
  );
 
  if($_[0] =~ /[a-zA-Z]/g) {
    $raw_addr = (gethostbyname($_[0]))[4];
    @octets = unpack("C4", $raw_addr);
    $host_name = join(".", @octets);
  } else {
    @bytes = split(/./, $_[0]);
    $packedaddr = pack("C4",@bytes);
    $host_name = (gethostbyaddr($packedaddr, 2))[0];
  }
 
  return($host_name);
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/7591490/viewspace-1033056/,如需轉載,請註明出處,否則將追究法律責任。

相關文章