Perform WHOIS Query with PHP

As a sort of follow-up to my earlier post about tracking search engine keywords, another useful source of information is in a visitor's IP addess. Querying WHOIS is a good first step, and it can be done very easily using PHP.

<?php

    function whoisQuery ($ip, $host = 'whois.arin.net', $port = 43, $max_hops = 3) {

        if (!preg_match("|[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}|", $ip)) {

            $ip = gethostbyname($ip);

        }

        // query whois
        $fp = fsockopen($host, $port, $errno, $errstr);

        // send over the ip
        fwrite($fp, $ip. "\r\n");

        while (!feof($fp)) {

            // get response line-by-line
            $buf = fgets($fp, 1024);

            if (trim($buf)) {

                // check for a referral server, and if found query it recursively
                if (preg_match("|^ReferralServer: whois://([^\n]+):([\d]+)|i", $buf, $matches)) {

                    if ($max_hops > 0) {

                        return whoisQuery($ip, $matches[1], $matches[2], $max_hops - 1);

                    }

                }

                $data .= $buf;

            }

        }

        fclose ($fp);

        return $data;

    }

?>

Comments (0)

Commenting has been disabled for this entry

If you'd like to discuss an aspect of this post, feel free to contact me via email.