gethostbyaddr

A. P. Harris (apharris@onshore.com)
Mon, 22 Jan 1996 18:31:21 -0600


------- =_aaaaaaaaaa0
Content-Type: text/plain; charset="us-ascii"
Content-ID: <2867.822357028.1@burrito.onshore.com>

[You (Paul.Beard@turner.com)]
>Anyone have clear examples for this function? I want to take an unresolved HTTP 
>server's access log and resolve the addresses, but the syntax of this function
>eludes me. 

I'm including a cute little script, 'canon'.  It covers a clean, perl4-friendly
method of doing this.  The script is from spaf@cs.purdue.edu (Gene Spafford).
Has nice comments too.

There are also perl5 modules for this function, I'm sure.

.....A. P. Harris...apharris@onShore.com...<URL:http://www.onShore.com/>

------- =_aaaaaaaaaa0
Content-Type: text/plain; charset="us-ascii"
Content-ID: <2867.822357028.2@burrito.onshore.com>

#!/usr/bin/perl
# 
#  "canon" program.  E. Spafford <spaf@cs.purdue.edu>
#
#From: spaf@cs.purdue.edu (Gene Spafford)
#Subject: Re: Get hostname from IP address
#Date: 16 Dec 1992 13:36:04 -0500
#
#It took me all of 10 minutes to build this Perl program a while ago.
#It took me more time today to add comments for releasing it than it
#did to write it!
#
#It is about 40 plus lines of code, but that is because I choose to
#write my programs to include error checking, print usage messages, and
#be readable. :-)  
#
#Something to take an IP number and turn it into a hostname can be done
#on the command line like so:
#perl -le 'print ((gethostbyaddr(pack("C4", split(/\./, shift)), 2))[0])' ip-#-arg
#(this assumes that AF_INET == 2 on your machine).
#This is not as general, nor is it as good form as what is below (I believe).
#

require "getopts.pl";
require "sys/socket.ph";

$usage = "usage: canon [-a] <name|#>\n";

&Getopts("ah") || die $usage;   # make sure we have proper options
$host = shift || die $usage;    # get a hostname/number

@a = ($host =~ m/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);        # IP number?

if (@a) {
    ($A, $junk, $junk, $junk, @addrs) = 
        gethostbyaddr(pack('C4', @a), &AF_INET);
} else {
    ($A, $junk, $junk, $junk, @addrs) = gethostbyname($host);
}

$A || &oops($?);

if ($opt_a) {
    foreach $addr (@addrs) {
        print join('.', unpack(C4, $addr)) . "\n";
    }
} else {
    print "$A\n";
}


sub oops {
   local($herr, %errm) = @_;
   require "netdb.ph";

   %errm = (
        &HOST_NOT_FOUND, "Host $host not found (authoritive)",
        &TRY_AGAIN, "Temporary failure looking up $host -- try again later",
        &NO_RECOVERY, "Non-recoverable error looking up $host",
        &NO_DATA, "$host is a valid name but no data is available"
           );

   die "$0: " . (defined($errm{$herr}) ? $errm{$herr} : 
        "Unknown error ($herr)") . ".\n";
}

------- =_aaaaaaaaaa0--