Recipe 16.9. Performing DNS Lookups

16.9.1. Problem

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

16.9.2. Solution

Use gethostbyname( ) and gethostbyaddr( ):

$ip   = gethostbyname(''); // $host = gethostbyaddr(''); //

16.9.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(''); print_r($hosts); $hosts = gethostbynamel(''); print_r($hosts); Array (     [0] =>     [1] =>     [2] =>     [3] =>     [4] =>     [5] =>     [6] =>     [7] =>     [8] => )

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('', $hosts, $weight); for ($i = 0; $i < count($hosts); $i++) {     echo "$weight[$i] $hosts[$i]\n"; } getmxrr('', $hosts, $weight); for ($i = 0; $i < count($hosts); $i++) {     echo "$weight[$i] $hosts[$i]\n"; } 5 1 1

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

16.9.4. See Also

Documentation on gethostbyname( ) at, gethostbyaddr( ), gethostbynamel( ) at, and getmxrr( ) at; PEAR's Net_DNS package at; DNS and BIND by Paul Albitz and Cricket Liu (O'Reilly).

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: