Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 789
Beier Avatar asked Sep 02 '09 19:09

Beier


2 Answers

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;
    }
}
like image 171
GZipp Avatar answered Nov 03 '22 03:11

GZipp


I think you should be able to get the IP address from the server with:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://stackoverflow.com");
curl_exec($ch);
$ip = curl_getinfo($ch,CURLINFO_PRIMARY_IP);
curl_close($ch);
echo $ip; // 151.101.129.69
like image 33
mmttato Avatar answered Nov 03 '22 04:11

mmttato