I want to know how to get client IP address using jQuery?
Is it possible? I know pure javascript can't, but got some code using JSONP
from Stack Overflow itself.
So, is there any workaround using jQuery?
This question is related to
javascript
jquery
ip-address
function GetUserIP(){
var ret_ip;
$.ajaxSetup({async: false});
$.get('http://jsonip.com/', function(r){
ret_ip = r.ip;
});
return ret_ip;
}
If you want to use the IP and assign it to a variable, Try this. Just call GetUserIP()
<html lang="en">
<head>
<title>Jquery - get ip address</title>
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
</head>
<body>
<h1>Your Ip Address : <span class="ip"></span></h1>
<script type="text/javascript">
$.getJSON("http://jsonip.com?callback=?", function (data) {
$(".ip").text(data.ip);
});
</script>
</body>
</html>
A simple AJAX call to your server, and then the serverside logic to get the ip address should do the trick.
$.getJSON('getip.php', function(data){
alert('Your ip is: ' + data.ip);
});
Then in php you might do:
<?php
/* getip.php */
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
print json_encode(array('ip' => $ip));
Source: Stackoverflow.com