Get json ip service

Getting client IP address is one common thing most of the web developers do, but getting the same with JavaScript is not possible as there is no notion of hosts or ip-addresses in the standard library.

True, there are many such services that provide IP in JSON format, but is it not better to trust yourself ;) ?

Just for the fun of it, made a simple service using PHP that would return the clients IP address in JSON and the same can be used in a client side scripting language like Jquery.

The php code :

<?php
header('content-type: application/json; charset=utf-8');
function get_ip()
{
if (getenv('HTTP_CLIENT_IP')) {
        $ip = getenv('HTTP_CLIENT_IP');
}
elseif (getenv('HTTP_X_FORWARDED_FOR')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
}
elseif (getenv('HTTP_X_FORWARDED')) {
        $ip = getenv('HTTP_X_FORWARDED');
}
elseif (getenv('HTTP_FORWARDED_FOR')) {
        $ip = getenv('HTTP_FORWARDED_FOR');
}
elseif (getenv('HTTP_FORWARDED')) {
        $ip = getenv('HTTP_FORWARDED');
}
else {
        $ip = $_SERVER['REMOTE_ADDR'];
}
                return $ip;
}

$ip = get_ip();
echo $_GET['callback'] . '(' .json_encode(array('ip' => $ip)). ');';

?>

Dismantling the code :

Note about the HTTP headers
"The X-Forwarded-For (XFF) HTTP header field is a de facto standard for identifying the originating IP address of a client connecting to a web server through an HTTP proxy or load balancer." But as there is no STD RFC for getting the client IP, fallbacks with different possible headers is used in the code above.

Caution : Anyone can forge HTTP_X_FORWARDED_FOR by using a proxy, so filtering or blocking an user with IP may not be fruitful always!

The content type indeed matters
According to RFC 4627 The MIME media type for JSON text is application/json. So the php script sets the content type to application/json.

Getting the JSON IP using JQUERY :

$.getJSON("http://h3manth.com/ip.php?callback=?",
    function(json){
       console.log( "IP : " + json.ip);
  });

Finally by doing a simple JSON service like this was fun and indeed did improvise an old L33t APIto have JSONP support.

Share this