Resolve IP address from hostname with perl.

Here is a small section of perl code that I stumbled upon that resolves an IP from a supplied hostname. Written by detour@metalshell.com.

use Socket;
use strict;
 
sub hostname {
  my (@bytes, @octets, $packedaddr, $raw_addr, $host_name, $ip);                                           
  if($_[0] =~ /[a-zA-Z]/g) {
     $raw_addr = (gethostbyname($_[0]))[4];                                                                
     @octets = unpack("C4", $raw_addr);                                                                    
     $host_name = join(".", @octets);                                                                      
  } else {
     @bytes = split(/\./, $_[0]);
     $packedaddr = pack("C4",@bytes);
     $host_name = (gethostbyaddr($packedaddr, 2))[0];                                                      
  }
  return($host_name);                                                                                      
}

Usage:

my $host_ip = hostname($host_name);

Thank you detour this code comes in very handy when I’m writing a bonehead perl script!

This entry was posted in Programming, Webhosting and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.