marco.shaw has asked for the wisdom of the Perl Monks concerning the following question:

Went searching. I need a simply way to return the hostname associated with an IP. I *just* want the hostname. I don't have net::nslookup installed for example. I was looking to have something simple and not have to install any modules. So obviously I also need something to strip out all of the nslookup verboseness...

Replies are listed 'Best First'.
Re: Simple nslookup
by jwkrahn (Abbot) on Feb 29, 2008 at 19:37 UTC
    I need a simply way to return the hostname associated with an IP.
    $ host yahoo.com yahoo.com has address 66.94.234.13 [ SNIP ] $ perl -MSocket -le'my $name = gethostbyaddr inet_aton( "66.94.234.13" + ), AF_INET; print $name' w2.rc.vip.scd.yahoo.com
Re: Simple nslookup
by Narveson (Chaplain) on Feb 29, 2008 at 19:18 UTC

    Regexp::Common

    I was looking to have something simple and not have to install any modules.

    To clarify: you would not actually have to install Regexp::Common to use one of its regular expressions. You can search for the regular expression that you need, copy the expression out of the module source code, then paste it into your own program.

      Erm, just how the frell is a regular expression going to do a reverse lookup on an IP address? I know there were some changes in the engine in 5.10, but really . . .

      (That inanity aside, gethostbyaddr that's been pointed out below is the easiest method presuming the underlying OS has a working resolver setup).

      The cake is a lie.
      The cake is a lie.
      The cake is a lie.

Re: Simple nslookup
by Khen1950fx (Canon) on Mar 03, 2008 at 06:36 UTC
    This script will give you an IP address and name for yahoo.com. Note: yahoo.com resolves to two IP addresses; hence, the script chooses one for you.

    Requires:
    nmap
    webscan.pl
    Nmap::Scanner
    Net::Nslookup

    #!/usr/bin/perl package WebScanner; use Net::Nslookup; use Nmap::Scanner::Util::BannerScanner; use vars qw(@ISA); @ISA = qw(Nmap::Scanner::Util::BannerScanner); my $name = Net::Nslookup->nslookup; $name = nslookup( domain => 'yahoo.com' ); print $name, "\n"; sub new { my $class = shift; my $self = $class->SUPER::new(); $self->regex('Server:\s*(.+)$'); $self->send_on_connect("HEAD / HTTP/1.0\r\n\r\n"); $self->add_scan_port(80); $self->add_scan_port(8080); $self->add_target( $_[0] || die "Need target in constructor!\n" ) +; return bless $self, $class; } 1; use lib 'lib'; use strict; my $web = WebScanner->new( $name || die "Missing host to scan!\n$0 host\n" ); $web->register_banner_found_event( sub { shift; print $_[0]->hostname( +), "\n"; } ); $web->scan();

    update: OK...to get just the name

    #!/usr/bin/perl use Net::Nslookup; my $name = Net::Nslookup->nslookup; $name = nslookup( domain => '66.94.234.13', type => 'PTR' ); print $name, "\n";