I would like to read my ip address from the following page(http://l2.io/ip or other) using javascript to save him in my variable "myIp".
function getMyIP() {
var myIp;
...
return myIp;
}
How can you do?
This question is related to
javascript
ip
If you face an issue of CORS, you can use https://api.ipify.org/.
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
publicIp = httpGet("https://api.ipify.org/");
alert("Public IP: " + publicIp);
I agree that using synchronous HTTP call is not good idea. You can use async ajax call then.
This pulls back client info as well.
var get = function(u){
var x = new XMLHttpRequest;
x.open('GET', u, false);
x.send();
return x.responseText;
}
JSON.parse(get('http://ifconfig.me/all.json'))
Well, if in the HTML you import a script...
<script type="text/javascript" src="//stier.linuxfaq.org/ip.php"></script>
You can then use the variable userIP (which would be the visitor's IP address) anywhere on the page.
To redirect: <script>if (userIP == "555.555.555.55") {window.location.replace("http://192.168.1.3/flex-start/examples/navbar-fixed-top/");}</script>
Or to show it on the page: document.write (userIP);
DISCLAIMER: I am the author of the script I said to import. The script comes up with the IP by using PHP. The source code of the script is below.
<?php
//Gets the IP address
$ip = getenv("REMOTE_ADDR") ;
Echo "var userIP = '" . $ip . "';";
?>
$.ajax({
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
alert(location.ip);
}
});
This will work https too
A more reliable REST endpoint would be http://freegeoip.net/json/
Returns the ip address along with the geo-location too. Also has cross-domain requests enabled (Access-Control-Allow-Origin: *) so you don't have to code around JSONP.
<script type="application/javascript">
function getip(json){
alert(json.ip); // alerts the ip address
}
</script>
<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"></script>
Source: Stackoverflow.com