Last Updated: February 25, 2016
·
963
· 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;

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#php
#ip
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside