本文分享二个perl的例子,学习下IP地址与主机名转换的方法。
例1,IP地址到主机名的转换
#!/usr/bin/perl
use Socket;
my $ADDR_PAT = /^d+.d+.d+.d+$/;
while (<>) {
chomp;
die "$_: Not a valid address" unless /$ADDR_PAT/o;
my $name = gethostbyaddr(inet_aton($_),AF_INET);
$name ||= '?';
print "$_ => $namen";
}
例2,perl实例之主机名到IP地址的转换。
#!/usr/bin/perl
use Socket;
my $packed_address = gethostbyname("localhost");
unless ($packed_address) {
print "$_ => ?n";
next;
}
my $dotted_quad = inet_ntoa($packed_address);
print "$_ => $dotted_quadn";