Last Updated: February 25, 2016
·
750
· ssv445

Find public IP of server

<?php

function getWebPage($url)
{
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

# try-1
$url = 'http://api.externalip.net/ip';
$content = getWebPage($url);
$ip = trim($content);

if(inet_pton($ip)){
return $ip;
}

#try-2
echo 'Fetching external IP from: http://checkip.dyndns.org:8245 ';
$html = getWebPage("http://checkip.dyndns.org:8245");
if(preg_match('/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/', $html, $matches) !== 0){
   return $matches[0];
}

return false;