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?
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?
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.
If you face an issue of CORS, you can use https://api.ipify.org/.
I agree that using synchronous HTTP call is not good idea. You can use async ajax call then.
Well, if in the HTML you import a 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 . "';"; ?>
This pulls back client info as well.
Checking your linked site, you may include a script tag passing a
?var=desiredVarName
parameter which will be set as a global variable containing the IP address:Demo
I believe I don't have to say that this can be easily spoofed (through either use of proxies or spoofed request headers), but it is worth noting in any case.
HTTPS support
In case your page is served using the
https
protocol, most browsers will block content in the same page served using thehttp
protocol (that includes scripts and images), so the options are rather limited. If you have < 5k hits/day, the Smart IP API can be used. For instance:Demo
Edit: Apparently, this
https
service's certificate has expired so the user would have to add an exception manually. Open its API directly to check the certificate state: https://smart-ip.net/geoip-jsonWith back-end logic
The most resilient and simple way, in case you have back-end server logic, would be to simply output the requester's IP inside a
<script>
tag, this way you don't need to rely on external resources. For example:PHP:
There's also a more sturdy PHP solution (accounting for headers that are sometimes set by proxies) in this related answer.
C#:
This will work https too