user156153 user156153 - 1 month ago 14
PHP Question

PHP Curl, retrieving Server IP Address

I'm using PHP CURL to send a request to a server. What do I need to do so the response from server will include that server's IP address?

Answer

This can be done with curl, with the advantage of having no other network traffic besides the curl request/response. DNS requests are made by curl to get the ip addresses, which can be found in the verbose report. So:

  • Turn on CURLOPT_VERBOSE.
  • Direct CURLOPT_STDERR to a "php://temp" stream wrapper resource.
  • Using *preg_match_all()*, parse the resource's string content for the ip address(es).
  • The responding server addresses will be in the match array's zero-key subarray.
  • The address of the server delivering the content (assuming a successful request) can be retrieved with end(). Any intervening servers' addresses will also be in the subarray, in order.

Demo:

$url = 'http://google.com';
$wrapper = fopen('php://temp', 'r+');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $wrapper);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$ips = get_curl_remote_ips($wrapper);
fclose($wrapper);

echo end($ips);  // 208.69.36.231

function get_curl_remote_ips($fp) 
{
    rewind($fp);
    $str = fread($fp, 8192);
    $regex = '/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/';
    if (preg_match_all($regex, $str, $matches)) {
        return array_unique($matches[0]);  // Array([0] => 74.125.45.100 [2] => 208.69.36.231)
    } else {
        return false;
    }
}
Comments