home *** CD-ROM | disk | FTP | other *** search
- Xref: sparky comp.unix.programmer:5717 comp.sources.wanted:5405 comp.lang.perl:7460
- Path: sparky!uunet!think.com!ames!purdue!not-for-mail
- From: spaf@cs.purdue.edu (Gene Spafford)
- Newsgroups: comp.unix.programmer,comp.sources.wanted,comp.lang.perl
- Subject: Re: Get hostname from IP address
- Date: 16 Dec 1992 13:36:04 -0500
- Organization: Department of Computer Sciences, Purdue University
- Lines: 68
- Message-ID: <1gnsukINN1hk@uther.cs.purdue.edu>
- References: <Bz2FFM.D4z@avalon.nwc.navy.mil>
- <1992Dec11.152438.18365@fwi.uva.nl> <1992Dec13.122835.28103@hyphen.com>
- <1992Dec13.180845.28960@hyphen.com>
- <1gj9afINN47k@mimas.cc.deakin.OZ.AU>
- <1992Dec16.015357.10437@hyphen.com>
- NNTP-Posting-Host: uther.cs.purdue.edu
- In-reply-to: dwight@hyphen.com's message of Wed, 16 Dec 1992 01:53:57 GMT
-
- 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).
-
-
- #!/usr/local/perl/perl
- #
- # "canon" program. E. Spafford <spaf@cs.purdue.edu>
- #
-
- 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";
- }
-
- --
- Gene Spafford
- Software Engineering Research Center & Dept. of Computer Sciences
- Purdue University, W. Lafayette IN 47907-1398
- Internet: spaf@cs.purdue.edu phone: (317) 494-7825
-