Translate an IP address to the corresponding hostname.
#!/usr/bin/perl -w
# ip2host.pl translates an IP address to the corresponding
# hostname. The subroutine ip2host() is invoked with an IP
# address as the only mandatory argument and returns the
# corresponding hostname.
#
# Copyright 2003, Ramiro Gómez.
#
# This program is free software; you can redistribute
# it and/or modify it under the same terms as Perl itself.
use strict;
use Socket;
# die if no argument was given
die "Usage: $0 IP-address\n" unless @ARGV;
my $ip_regex = qr(^\d+\.\d+\.\d+\.\d+$); # precompile regex for IP addresses
my $hostname = ip2host( shift );
print $hostname, "\n";
sub ip2host {
my $ip_addr = shift;
# check the pattern of supplied IP address
die "You didn't supply a valid IP address\n" unless $ip_addr =~ $ip_regex;
my $host = gethostbyaddr( inet_aton( $ip_addr ), AF_INET );
die "IP address $ip_addr doesn't exist.\n" unless $host;
return $host;
}
Post new comment