15

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?

moooeeeep
  • 31,622
  • 22
  • 98
  • 187
Milton90
  • 547
  • 2
  • 7
  • 15
  • 1
    possible duplicate of [Get Client IP using just Javascript?](http://stackoverflow.com/questions/391979/get-client-ip-using-just-javascript) – PSL Jul 01 '13 at 23:00
  • The other question asks for a client-side JS solution. In contrast, this question asks about retrieving the IP address via some remote web service. – moooeeeep Jun 02 '16 at 14:28

7 Answers7

35

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:

<script type="text/javascript" src="http://l2.io/ip.js?var=myip"></script>
                                                      <!-- ^^^^ -->
<script>alert(myip);</script>

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 the http 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:

<script>
var myip;
function ip_callback(o) {
    myip = o.host;
}
</script>
<script src="https://smart-ip.net/geoip-json?callback=ip_callback"></script>
<script>alert(myip);</script>

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-json


With 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:

<script>var myip = '<?php echo $_SERVER['REMOTE_ADDR']; ?>';</script>

There's also a more sturdy PHP solution (accounting for headers that are sometimes set by proxies) in this related answer.

C#:

<script>var myip = '<%= Request.UserHostAddress %>';</script>
Community
  • 1
  • 1
Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
  • 1
    I tried it locally with Aptana studio and it works. But when I load it on my web page says "undefined" – Milton90 Jul 01 '13 at 23:12
  • Weird, have you included both script tags one after another? This should work as long as the site you're pinging is up. – Fabrício Matté Jul 01 '13 at 23:15
  • The best approach, in case you have server-side logic, would be echoing the IP the user used to request the page. E.g. for PHP: `` – Fabrício Matté Jul 01 '13 at 23:17
  • and in myscript I try to use myip – Milton90 Jul 01 '13 at 23:18
  • ^ I believe your first script's `src` has `http://` which Stack Overflow stripped 'cause you didn't format as code, well it should work fine. Maybe do a Ctrl+F5 after uploading the edited files to ensure that it is not a caching issue. `=]` – Fabrício Matté Jul 01 '13 at 23:21
  • 1
    If you're using Chrome, check if the request is being made in Dev Tools (F12)'s Network tab: http://i.imgur.com/2oC7qal.png if the request doesn't appear there, check the page source to see if the script is actually there. – Fabrício Matté Jul 01 '13 at 23:25
  • 1
    And finally make sure that you don't have `var myip;` inside of your script. And that you don't have `"use strict";` in the global scope (haven't tested but it might break due to the way the l2.io sets the global var) – Fabrício Matté Jul 01 '13 at 23:30
  • Yes I use Chrome, in Dev Tools I read : blocked The page https://mypage... ran an insecure content from http://l2.io/ip.js?var=myip – Milton90 Jul 01 '13 at 23:43
  • Is your site running under `https`? I guess that's the issue. You won't be able to load data from `http` if so. – Fabrício Matté Jul 01 '13 at 23:45
  • mmm...I need to have it in https. Is there a way to get the ip? – Milton90 Jul 01 '13 at 23:49
  • If you have a back-end server language, using that to get the user IP will be much simpler, secure and faster than relying on external resources. Else, if you have a static page, you'll need to use another site that offers an https version. I'll look for one meanwhile. – Fabrício Matté Jul 01 '13 at 23:50
  • Ok, thanks. Before I used a get request to http://api.hostip.info/get_html.php and it worked but now the service is down. – Milton90 Jul 01 '13 at 23:55
  • I've found another service but it is over quota apparently https://jsonip.appspot.com/?callback=getip – Fabrício Matté Jul 01 '13 at 23:57
  • I tried it yesterday and it worked but I did not try if it goes in https. – Milton90 Jul 02 '13 at 00:01
  • I think smart-ip.net functions but stops me jquery and with https doesn't work – Milton90 Jul 02 '13 at 00:27
  • That looks a bit weird, don't forget to use the `https` version of the jQuery CDN as well. `;)` – Fabrício Matté Jul 02 '13 at 00:34
  • It works! I tried as you wrote ... instead of using jQuery and it works well with smart-ip.net. Thank a lot! – Milton90 Jul 02 '13 at 00:38
  • Why need to rely on 3rd party server? This wont work if the internet connection is not available! – Rafique Mohammed Sep 12 '15 at 11:53
  • @RafiqueMohammed well, that's because browsers do not provide any API to get the machine IP via vanilla JavaScript yet. Also, note that a given machine may be connected to multiple networks at the same time and thus have multiple IPs (up to one IP per network interface). – Fabrício Matté Sep 15 '15 at 16:46
14
    $.ajax({
        url: '//freegeoip.net/json/',
        type: 'POST',
        dataType: 'jsonp',
        success: function(location) {
            alert(location.ip);
        }
    });

This will work https too

Ranjit Kumar
  • 273
  • 3
  • 16
9

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.

epicwhale
  • 1,835
  • 18
  • 26
4

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.

Soumya Kanti
  • 1,429
  • 1
  • 17
  • 28
1
    <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>
bd_person
  • 23
  • 1
  • 1
  • 6
0

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'))
C B
  • 12,482
  • 5
  • 36
  • 48
0

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 . "';"; ?>