user156153 user156153 - 1 year ago 219
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 Source

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:

  • 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.


$url = '';
$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);
$ips = get_curl_remote_ips($wrapper);

echo end($ips);  //

function get_curl_remote_ips($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] => [2] =>
    } else {
        return false;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download