Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Any way in Perl to get the name of a server by using the IP address? I have an IP address and want to get the Host name of this IP address. This is not working for me?
foreach $host (@ARGV) { ($name, $aliases, $addrtype, $length, @addrs) = gethostbyname($host); #gethostbyname IS A PERL function? print "$host:\n"; foreach $a (@addrs) { $i = join(".", unpack("C4", $a)); if( ! $i ) { print ">>>>>>$i<<<<<<\n"; print "NOT FOUND\n"; } else { print "$i\n"; } } }

Replies are listed 'Best First'.
Re: hostname from ip
by bart (Canon) on Oct 02, 2003 at 14:24 UTC
    Wrong function. The one you're using is to look up the IP by name.
    print join ".", unpack 'C*', scalar gethostbyname('mediamind.be');
    -->
    66.33.0.165
    
    The fucntion you need to use, is gethostbyaddr(). Socket is used for the constant AF_INET, though you could use it for the more robust function inet_aton(), too, instead of the pack+split. See the example in perlfunc:gethostbyaddr.
    use strict; my $ip = join ".", unpack 'C*', scalar gethostbyname('mediamind.be'); print "IP = $ip\n"; use Socket; my @result = gethostbyaddr pack('C*', split /\./, $ip), AF_INET; use Data::Dumper; $Data::Dumper::Useqq = 1; print Dumper @result;
    -->
    IP = 66.33.0.165
    $VAR1 = "mediamind.be";
    $VAR2 = "";
    $VAR3 = 2;
    $VAR4 = 4;
    $VAR5 = "B!\0\245";
    
Re: hostname from ip
by jeffa (Bishop) on Oct 02, 2003 at 13:27 UTC
    The Perl Cookbook Recipe 17.7 discusses this, but you have to have a SOCKET first. Take a look at Net::DNS and Acme::DNS::Correct. From the docs:
    use strict; use warnings; use Net::DNS; use Acme::DNS::Correct 'sneaky'; use Data::Dumper; my $res = Net::DNS::Resolver->new; my $query = $res->search("host.example.com"); if ($query) { foreach my $rr ($query->answer) { next unless $rr->type eq "A"; print $rr->address, "\n"; } } else { warn "query failed: ", $res->errorstring, "\n"; }

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    

      Far too complex!

      #! /usr/bin/perl -w use strict; use Socket; for( @ARGV ) { if( my $host = gethostbyaddr( inet_aton($_), AF_INET )) { print "$_ is $host\n"; } else { print "$_ NXDOMAIN\n"; } }

      Works on my machine :)

      Note that this will return one record. If you are doing funky things with multiple A or PTR records it might miss the information you're interested in. In which case the Net::DNS module will let you iterate through the RR set. Otherwise it's overkill.

Re: hostname from ip
by tachyon (Chancellor) on Oct 02, 2003 at 15:22 UTC
    use Socket; my $ip = '127.0.0.1'; my $name = gethostbyaddr(inet_aton($ip), AF_INET ); print $name ? $name : "NOT FOUND";

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print