home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1992 March / Source_Code_CD-ROM_Walnut_Creek_March_1992.iso / usenet / altsrcs / 3 / 3624 / resolver.pl < prev    next >
Encoding:
Perl Script  |  1991-07-13  |  2.0 KB  |  76 lines

  1. #!/usr2/new/bin/perl                                  #-*-perl-*-
  2. # a subroutine to resolve a Internet host name to IP address
  3. # Copyright (C) Khun Yee Fung (clipper@csd.uwo.ca) 1991
  4. # You can do anything to this file except to sell it and/or pretend
  5. # you wrote it. You must preserve the copyright notice.
  6. package resolver;
  7.  
  8. sub main'resolver {
  9.   local($sockaddr) = 'S n a4 x8';
  10.   local($hostname, $server) = @_;
  11.   local($port) = 53;
  12.  
  13.   if ($server =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/) {
  14.       $saddr = pack('CCCC', $1, $2, $3, $4);
  15.   }
  16.   elsif (!(($name, $aliases, $type, $len, $saddr) = gethostbyname($server))) {
  17.       return 0;
  18.   }
  19.   local($sin) = pack($sockaddr, 2, $port, $saddr);
  20.  
  21.   socket(NSERVER, 2, 1, 0) || return 0;
  22.   connect(NSERVER, $sin) || return 0;
  23.  
  24.   select(NSERVER); $| = 1; select(STDOUT); $| = 1;
  25.  
  26.   local($len) = 18 + length($hostname);
  27.   local(@names) = split('\.', $hostname);
  28.   local($head) = pack('S6', 319, 256, 1, 0, 0, 0);
  29.   print NSERVER pack('S', $len), $head;
  30.   local($arg, $response);
  31.   foreach $arg (@names) {
  32.     print NSERVER pack('C', length($arg)), $arg;
  33.   }
  34.   print NSERVER pack('CS2', 0, 1, 1);
  35.  
  36.   read(NSERVER, $len, 2);
  37.   read(NSERVER, $response, unpack('S', $len));
  38.   close NSERVER;
  39.  
  40.   local(@shead) = unpack('S6', $response);
  41.   ($shead[1] & 0x0F) == 0 || return 0;
  42.  
  43.   local($in) = 12;
  44.   local($ans) = $shead[2];
  45.   local($c);
  46.   while ($ans > 0) {
  47.     while (($c = ord(substr($response, $in++, 1))) != 0) {
  48.       $in += $c;
  49.     }
  50.     $in += 4;
  51.     $ans--;
  52.   }
  53.  
  54.   $ans = $shead[3];
  55.   local($type, $rdlength, $rdata);
  56.   local(@return);
  57.   while ($ans > 0) {
  58.     while (($c = ord(substr($response, $in++, 1))) != 0) {
  59.       ($c & 0xc0) != 0xc0 || $in++, last;
  60.       $in += $c;
  61.     }
  62.     $type = substr($response, $in, 2);
  63.     $in += 8;
  64.     $rdlength = unpack('n', substr($response, $in, 2));
  65.     $in += 2;
  66.     $rdata = substr($response, $in, $rdlength);
  67.     if (unpack('S', $type) == 1) {
  68.     push(@return, $rdata);
  69.     }
  70.     $in += $rdlength;
  71.     $ans--;
  72.   }
  73.   return @return;
  74. }
  75. 1;
  76.