start page | rating of books | rating of authors | reviews | copyrights

Book HomePHP CookbookSearch this book

17.10. Performing DNS Lookups

17.10.1. Problem

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

17.10.2. Solution

Use gethostbyname( ) and gethostbyaddr( ):

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

17.10.3. 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( ), gethostbynamel( ) returns an array, not a string.

You can also do more complicated DNS-related tasks. For instance, you can get the MX records using getmxrr( ):

getmxrr('yahoo.com', $hosts, $weight);
for ($i = 0; $i < count($hosts); $i++) {
    echo "$weight[$i] $hosts[$i]\n";
}
5 mx4.mail.yahoo.com
1 mx2.mail.yahoo.com
1 mx1.mail.yahoo.com

To perform zone transfers, dynamic DNS updates, and more, see PEAR's Net_DNS package.

17.10.4. See Also

Documentation on gethostbyname( ) at http://www.php.net/gethostbyname, gethostbyaddr( ) http://www.php.net/gethostbyaddr, gethostbyaddrl( ) at http://www.php.net/gethostbyaddrl, and getmxrr( ) at http://www.php.net/getmxrr; PEAR's Net_DNS package at http://pear.php.net/package-info.php?package=Net_DNS; DNS and BIND by Paul Albitz and Cricket Liu (O'Reilly) .



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.