PHP Curl, retrieving Server IP Address

前端 未结 6 1171
迷失自我
迷失自我 2021-02-08 21:52

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?

6条回答
  •  难免孤独
    2021-02-08 22:37

    I don't think there is a way to get that IP address directly from curl.
    But something like this could do the trick :

    First, do the curl request, and use curl_getinfo to get the "real" URL that has been fetched -- this is because the first URL can redirect to another one, and you want the final one :

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://www.google.com/");
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $content = curl_exec($ch);
    $real_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    curl_close($ch);
    var_dump($real_url);    // http://www.google.fr/
    

    Then, use parse_url to extract the "host" part from that final URL :

    $host = parse_url($real_url, PHP_URL_HOST);
    var_dump($host);        // www.google.fr
    

    And, finally, use gethostbyname to get the IP address that correspond to that host :

    $ip = gethostbyname($host);
    var_dump($ip);          // 209.85.227.99
    

    Well...
    That's a solution ^^ It should work in most cases, I suppose -- though I'm not sure you would always get the "correct" result if there is some kind of load-balancing mecanism...

提交回复
热议问题