Articles

PHP Reverse DNS lookup

Author: nathacof
Published: Friday 17th of July 2009

Reverse DNS lookup is a useful way to loosely verify the identity of a server, and is commonly used in SMTP email verification. Typically the owner of the IP must host the DNS record for the IP's PTR record, however it is possible for an entity to delegate RDNS lookups to another host. To obtain a RDNS record for an IP address you simply reverse the octets of the IP, and tack on .in-addra.arpa to the result, so a RDNS lookup on my IP would really be a PTR lookup on the zone, 17.12.12.76.in-addr.arpa

$ dig +short neranjara.org
76.12.12.17
$ dig +short PTR 17.12.12.76.in-addr.arpa
vps.neranjara.org.

Function

Here's a PHP function to do this for you.

<?php
function getRdnsRecord($ip) {
/*
 * Validate IP
 */ 
if(!ip2long($ip)) {
   trigger_error("Error: Invalid IP",
                 E_USER_NOTICE);
   return FALSE;
}

/*
 * Break the IP into 4 octets
 */
$array = explode(".", $ip, 4);

/*
 * Reverse the order of the octets
 */
$array = array_reverse($array);

/*
 * Assemble our zone
 */
$zone = implode(".", $array) 
      . ".in-addr.arpa";

/*
 * Return the Resulting record
 */
return dns_get_record($zone, DNS_PTR);
}

Usage

<pre>
<?php var_dump(getRdnsRecord('76.12.12.17'));?>
</pre>
array(1) {
  [0]=>
  array(5) {
    ["host"]=>
    string(24) "17.12.12.76.in-addr.arpa"
    ["type"]=>
    string(3) "PTR"
    ["target"]=>
    string(17) "vps.neranjara.org"
    ["class"]=>
    string(2) "IN"
    ["ttl"]=>
    int(3545)
  }
}

Of course there is always the PHP function gethostbyaddr(), however I've heard reports that this function is rather slow. I didn't know it existed until after I initially wrote this functionality for my site. I haven't done any comparisons speed wise either way. :oP

If nothing else I hope this post has been educational. That's it. Have fun!

Article Search

Social Networks