17.9. Performing DNS Lookups

Problem

You want to look up a domain name or an IP address.

Solution

Use gethostbyname( ) and gethostbyaddr( ):

$ip   = gethostbyname('www.example.com'); // 192.0.34.72
$host = gethostbyaddr('192.0.34.72'); // www.example.com

Discussion

You can’t trust the name returned by gethostbyaddr( ) . A DNS server with authority for a particular IP address can return any hostname at all. Usually, administrators set up DNS servers to reply with a correct hostname, but a malicious user may configure her DNS server to reply with incorrect hostnames. One way to combat this trickery is to call gethostbyname( ) on the hostname returned from gethostbyaddr( ) and make sure the name resolves to the original IP address.

If either function can’t successfully look up the IP address or the domain name, it doesn’t return false, but instead returns the argument passed to it. To check for failure, do this:

if ($host == ($ip = gethostbyname($host))) {
    // failure
}

This assigns the return value of gethostbyname( ) to $ip and also checks that $ip is not equal to the original $host.

Sometimes a single hostname can map to multiple IP addresses. To find all hosts, use gethostbynamel( ) :

$hosts = gethostbynamel('www.yahoo.com');
print_r($hosts);
Array
               (
                   [0] => 64.58.76.176
                   [1] => 64.58.76.224
                   [2] => 64.58.76.177
                   [3] => 64.58.76.227
                   [4] => 64.58.76.179
                   [5] => 64.58.76.225
                   [6] => 64.58.76.178
                   [7] => 64.58.76.229
                   [8] => 64.58.76.223
               )

In contrast to gethostbyname( ) and gethostbyaddr( ) ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.