Simple DNS Lookups


You want to find the IP address of a host or turn an IP address into a name. Network servers do this to authenticate their clients, and clients do it when the user gives them a hostname but Perl’s socket library requires an IP address. Furthermore, many servers produce log files containing IP addresses, but hostnames are more useful to analysis software and humans.


If you have a name like, use gethostbyname if you want all the addresses:

use Socket;

@addresses = gethostbyname($name)   or die "Can't resolve $name: $!\n";
@addresses = map { inet_ntoa($_) } @addresses[4 .. $#addresses];
# @addresses is a list of IP addresses ("", "")

Or, use inet_aton if you only need the first:

use Socket;

$address = inet_ntoa(inet_aton($name));
# $address is a single IP address ""

If you have an IP address like "", use:

use Socket;

$name = gethostbyaddr(inet_aton($address), AF_INET)
            or die "Can't resolve $address: $!\n";
# $name is the hostname ("")


This process is complicated because the functions are mere wrappers for the C system calls, so this means you have to convert IP addresses from ASCII strings ("") into their C structures. The standard Socket module gives you inet_aton to convert from ASCII to the packed numeric format and inet_ntoa to convert back:

use Socket;
$packed_address = inet_aton("");
$ascii_address  = inet_ntoa($packed_address);


Get Perl Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.