How to get client's IP address using JavaScript?

Go To StackoverFlow.com

561

I need to somehow retrieve the client's IP address using JavaScript; no server side code, not even SSI.

However, I'm not against using a free 3rd party script/service.

2008-12-24 18:22
by FlySwat


557

I would use a web service that can return JSON (along with jQuery to make things simpler). Below are all the free active IP lookup services I could find and the information they return. If you know of any more, then please add a comment and I'll update this answer.


DB-IP

Try it: http://api.db-ip.com/addrinfo?api_key=<your api key>&addr=<ip address>

Returns:

{
  "address": "116.12.250.1",
  "country": "SG",
  "stateprov": "Central Singapore",
  "city": "Singapore"
}

Limitations:

  • 2,500 requests per day
  • Doesn't support JSONP callbacks
  • Requires IP address parameter
  • Requires an email address to get your API key
  • No SSL (https) with the free plan

Geobytes

Try it: http://gd.geobytes.com/GetCityDetails

$.getJSON('http://gd.geobytes.com/GetCityDetails?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "geobytesforwarderfor": "",
  "geobytesremoteip": "116.12.250.1",
  "geobytesipaddress": "116.12.250.1",
  "geobytescertainty": "99",
  "geobytesinternet": "SA",
  "geobytescountry": "Saudi Arabia",
  "geobytesregionlocationcode": "SASH",
  "geobytesregion": "Ash Sharqiyah",
  "geobytescode": "SH",
  "geobyteslocationcode": "SASHJUBA",
  "geobytescity": "Jubail",
  "geobytescityid": "13793",
  "geobytesfqcn": "Jubail, SH, Saudi Arabia",
  "geobyteslatitude": "27.004999",
  "geobyteslongitude": "49.660999",
  "geobytescapital": "Riyadh ",
  "geobytestimezone": "+03:00",
  "geobytesnationalitysingular": "Saudi Arabian ",
  "geobytespopulation": "22757092",
  "geobytesnationalityplural": "Saudis",
  "geobytesmapreference": "Middle East ",
  "geobytescurrency": "Saudi Riyal",
  "geobytescurrencycode": "SAR",
  "geobytestitle": "Saudi Arabia"
}

Limitations:

  • 16,384 requests per hour
  • No SSL (https) with the free plan
  • Can return the wrong location (I'm in Singapore, not Saudi Arabia)

GeoIPLookup.io

Try it: https://json.geoiplookup.io/api

$.getJSON('https://json.geoiplookup.io/api?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
    "ip": "116.12.250.1",
    "isp": "SGPOST",
    "org": "Singapore Post Ltd",
    "hostname": "116.12.250.1",
    "longitude": "103.807",
    "latitude": "1.29209",
    "postal_code": "",
    "city": "Singapore",
    "country_code": "SG",
    "country_name": "Singapore",
    "continent_code": "AS",
    "region": "Central Singapore",
    "district": "",
    "timezone_name": "Asia\/Singapore",
    "connection_type": "",
    "asn": "AS3758 SingNet",
    "currency_code": "SGD",
    "currency_name": "Singapore Dollar",
    "success": true
}

Limitations:

  • Unknown

geoPlugin

Try it: http://www.geoplugin.net/json.gp

$.getJSON('http://www.geoplugin.net/json.gp?jsoncallback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "geoplugin_request": "116.12.250.1",
  "geoplugin_status": 200,
  "geoplugin_credit": "Some of the returned data includes GeoLite data created by MaxMind, available from <a href=\\'http://www.maxmind.com\\'>http://www.maxmind.com</a>.",
  "geoplugin_city": "Singapore",
  "geoplugin_region": "Singapore (general)",
  "geoplugin_areaCode": "0",
  "geoplugin_dmaCode": "0",
  "geoplugin_countryCode": "SG",
  "geoplugin_countryName": "Singapore",
  "geoplugin_continentCode": "AS",
  "geoplugin_latitude": "1.2931",
  "geoplugin_longitude": "103.855797",
  "geoplugin_regionCode": "00",
  "geoplugin_regionName": "Singapore (general)",
  "geoplugin_currencyCode": "SGD",
  "geoplugin_currencySymbol": "&#36;",
  "geoplugin_currencySymbol_UTF8": "$",
  "geoplugin_currencyConverter": 1.4239
}

Limitations:

  • 120 requests per minute
  • No SSL (https) with the free plan

Hacker Target

Try it: https://api.hackertarget.com/geoip/?q=<ip address>

Returns:

IP Address: 116.12.250.1
Country: SG
State: N/A
City: Singapore
Latitude: 1.293100
Longitude: 103.855797

Limitations:

  • 50 requests per day
  • Doesn't support JSONP callbacks
  • Requires IP address parameter
  • Returns plain text

ipapi.co

Try it: https://ipapi.co/json/

$.getJSON('https://ipapi.co/json/', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "ip": "116.12.250.1",
  "city": "Singapore",
  "region": "Central Singapore Community Development Council",
  "country": "SG",
  "country_name": "Singapore",
  "postal": null,
  "latitude": 1.2855,
  "longitude": 103.8565,
  "timezone": "Asia/Singapore"
}

Limitations:

  • 1,000 requests per day
  • Requires SSL (https)

IP-API.com

Try it: http://ip-api.com/json

$.getJSON('http://ip-api.com/json?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "as": "AS3758 SingNet",
  "city": "Singapore",
  "country": "Singapore",
  "countryCode": "SG",
  "isp": "SingNet Pte Ltd",
  "lat": 1.2931,
  "lon": 103.8558,
  "org": "Singapore Telecommunications",
  "query": "116.12.250.1",
  "region": "01",
  "regionName": "Central Singapore Community Development Council",
  "status": "success",
  "timezone": "Asia/Singapore",
  "zip": ""
}

Limitations:

  • 150 requests per minute
  • No SSL (https) with the free plan

Ipdata.co

Try it: https://api.ipdata.co

$.getJSON('https://api.ipdata.co', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "ip": "116.12.250.1",
  "city": "Singapore",
  "region": "Central Singapore Community Development Council",
  "region_code": "01",
  "country_name": "Singapore",
  "country_code": "SG",
  "continent_name": "Asia",
  "continent_code": "AS",
  "latitude": 1.2931,
  "longitude": 103.8558,
  "asn": "AS3758",
  "organisation": "SingNet",
  "postal": "",
  "calling_code": "65",
  "flag": "https://ipdata.co/flags/sg.png",
  "emoji_flag": "\ud83c\uddf8\ud83c\uddec",
  "emoji_unicode": "U+1F1F8 U+1F1EC",
  "is_eu": false,
  "languages": [
    {
      "name": "English",
      "native": "English"
    },
    {
      "name": "Malay",
      "native": "Bahasa Melayu"
    },
    {
      "name": "Tamil",
      "native": "\u0ba4\u0bae\u0bbf\u0bb4\u0bcd"
    },
    {
      "name": "Chinese",
      "native": "\u4e2d\u6587"
    }
  ],
  "currency": {
    "name": "Singapore Dollar",
    "code": "SGD",
    "symbol": "S$",
    "native": "$",
    "plural": "Singapore dollars"
  },
  "time_zone": {
    "name": "Asia/Singapore",
    "abbr": "+08",
    "offset": "+0800",
    "is_dst": false,
    "current_time": "2018-05-09T12:28:49.183674+08:00"
  },
  "threat": {
    "is_tor": false,
    "is_proxy": false,
    "is_anonymous": false,
    "is_known_attacker": false,
    "is_known_abuser": false,
    "is_threat": false,
    "is_bogon": false
  }
}

Limitations:

  • 1,500 requests per day
  • Requires an email address to get your API key
  • Requires SSL (https)

IP Find

Try it: https://ipfind.co/me?auth=<your api key>

$.getJSON('https://ipfind.co/me?auth=<your_api_key>', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "ip_address": "116.12.250.1",
  "country": "Singapore",
  "country_code": "SG",
  "continent": "Asia",
  "continent_code": "AS",
  "city": "Singapore",
  "county": null,
  "region": "Central Singapore",
  "region_code": "01",
  "timezone": "Asia/Singapore",
  "owner": null,
  "longitude": 103.8565,
  "latitude": 1.2855,
  "currency": "SGD",
  "languages": [
    "cmn",
    "en-SG",
    "ms-SG",
    "ta-SG",
    "zh-SG"
  ]
}

Limitations:

  • 300 requests per day
  • Requires registration to get your API key

ipgeolocation

Try it: https://api.ipgeolocation.io/ipgeo?apiKey=<your api key>

$.getJSON('https://api.ipgeolocation.io/ipgeo?apiKey=<your_api_key>', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "ip": "116.12.250.1",
  "continent_code": "AS",
  "continent_name": "Asia",
  "country_code2": "SG",
  "country_code3": "SGP",
  "country_name": "Singapore",
  "country_capital": "Singapore",
  "state_prov": "Central Singapore",
  "district": "",
  "city": "Singapore",
  "zipcode": "",
  "latitude": "1.29209",
  "longitude": "103.807",
  "is_eu": false,
  "calling_code": "+65",
  "country_tld": ".sg",
  "languages": "cmn,en-SG,ms-SG,ta-SG,zh-SG",
  "country_flag": "https://ipgeolocation.io/static/flags/sg_64.png",
  "isp": "SGPOST",
  "connection_type": "",
  "organization": "Singapore Post Ltd",
  "geoname_id": "1880252",
  "currency": {
    "name": "Dollar",
    "code": "SGD"
  },
  "time_zone": {
    "name": "Asia/Singapore",
    "offset": 8,
    "is_dst": false,
    "current_time": "2018-06-12 09:06:49.028+0800"
  }
}

Limitations:

  • 50,000 requests per month
  • Requires registration to get your API key

ipify

Try it: https://api.ipify.org/?format=json

$.getJSON('https://api.ipify.org?format=jsonp&callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "ip": "116.12.250.1"
}

Limitations:

  • None

IPInfoDB

Try it: https://api.ipinfodb.com/v3/ip-city/?key=<your api key>&format=json

$.getJSON('https://api.ipinfodb.com/v3/ip-city/?key=<your_api_key>&format=json&callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "statusCode": "OK",
  "statusMessage": "",
  "ipAddress": "116.12.250.1",
  "countryCode": "SG",
  "countryName": "Singapore",
  "regionName": "Singapore",
  "cityName": "Singapore",
  "zipCode": "048941",
  "latitude": "1.28967",
  "longitude": "103.85",
  "timeZone": "+08:00"
}

Limitations:

  • Two requests per second
  • Requires registration to get your API key

ipinfo.io

Try it: https://ipinfo.io/json

$.getJSON('https://ipinfo.io/json', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "ip": "116.12.250.1",
  "hostname": "No Hostname",
  "city": "Singapore",
  "region": "Central Singapore Community Development Council",
  "country": "SG",
  "loc": "1.2931,103.8558",
  "org": "AS3758 SingNet"
}

Limitations:

  • 1,000 requests per day

ipstack (formerly freegeoip.net)

Try it: http://api.ipstack.com/<ip address>?access_key=<your api key>

$.getJSON('http://api.ipstack.com/<ip_address>?access_key=<your_api_key>', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
    "ip": "116.12.250.1",
    "type": "ipv4",
    "continent_code": "AS",
    "continent_name": "Asia",
    "country_code": "SG",
    "country_name": "Singapore",
    "region_code": "01",
    "region_name": "Central Singapore Community Development Council",
    "city": "Singapore",
    "zip": null,
    "latitude": 1.2931,
    "longitude": 103.8558,
    "location": {
        "geoname_id": 1880252,
        "capital": "Singapore",
        "languages": [{
            "code": "en",
            "name": "English",
            "native": "English"
        },
        {
            "code": "ms",
            "name": "Malay",
            "native": "Bahasa Melayu"
        },
        {
            "code": "ta",
            "name": "Tamil",
            "native": "\u0ba4\u0bae\u0bbf\u0bb4\u0bcd"
        },
        {
            "code": "zh",
            "name": "Chinese",
            "native": "\u4e2d\u6587"
        }],
        "country_flag": "http:\/\/assets.ipstack.com\/flags\/sg.svg",
        "country_flag_emoji": "\ud83c\uddf8\ud83c\uddec",
        "country_flag_emoji_unicode": "U+1F1F8 U+1F1EC",
        "calling_code": "65",
        "is_eu": false
    }
}

Limitations:

  • 10,000 requests per month
  • Requires IP address parameter
  • Requires registration to get your API key
  • No SSL (https) with the free plan

jsonip.com

Try it: https://jsonip.com

$.getJSON('https://jsonip.com/?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "ip": "116.12.250.1",
  "about": "/about",
  "Pro!": "http://getjsonip.com",
  "reject-fascism": "Liberal America will prevail"
}

Limitations:

  • The response includes upsell and politics

JSON Test

Try it: http://ip.jsontest.com/

$.getJSON('http://ip.jsontest.com/?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "ip": "116.12.250.1"
}

Limitations:

  • No SSL (https)
  • Goes down a lot (over quota), so I wouldn't use it for production
  • Returns IPv6 address if you have one, which may not be what you want

Nekudo

Try it: https://geoip.nekudo.com/api

$.getJSON('https://geoip.nekudo.com/api', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "city": "Singapore",
  "country": {
    "name": "Singapore",
    "code": "SG"
  },
  "location": {
    "accuracy_radius": 50,
    "latitude": 1.2855,
    "longitude": 103.8565,
    "time_zone": "Asia/Singapore"
  },
  "ip": "116.12.250.1"
}

Limitations:

  • Blocked by ad blockers using the EasyPrivacy list

Stupid Web Tools

Try it: http://www.stupidwebtools.com/api/my_ip.json

$.getJSON('http://www.stupidwebtools.com/api/my_ip.json', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "my_ip": {
    "ip": "116.12.250.1",
    "others": []
  }
}

Limitations:

  • No SSL (https)

Keep in mind that since these are all free services, your mileage may vary in terms of exceeding quota and uptime, and who knows when/if they will be taken offline down the road (exhibit A: Telize). Most of these services also offer a paid tier in case you want more features like SSL support.

Also, as skobaljic noted in the comments below, the request quotas are mostly academic since this is happening client-side and most end users will never exceed the quota.

UPDATES

2016-02-01 04:40
by thdoan
I would note that for jsonip.com, it will return only your IPv6 address if you have one, which could be undesirable depending on how you're using the information. But +1 for the excellent examples - Matt 2016-03-14 21:20
Are any of these HTTPS - mynameisnafe 2016-04-05 19:30
if someone gets problem with www.geoplugin.net/json.gp?jsoncallback=? Then use only www.geoplugin.net/json.gp will give proper response for ASP.NET. The first URL created problem for me - farhangdon 2016-04-18 17:23
All of these limitations usually mean nothing, cause it is a client side scripting. We do not expect a visitor to refresh a page 2,500 times, it has no sense - skobaljic 2016-09-15 00:33
@skobaljic The limitations don't generally apply to end users, but sites with millions of daily visitors may run into the quota and be forced on to a paid tier - thdoan 2016-09-15 02:59
Exactly opposite to truth, it is the client who consumes the API, not a website domain and therefore there may be only a couple of requests per client, maybe one, maybe 10, but never thousands - skobaljic 2016-09-15 11:34
@skobaljic Oh yeah, you are right about the client consuming the API since it's JavaScript after all, but are you sure the request is counted per client and not an aggregate usage of the service from all clients? Actually, I'm pretty sure ipinfo.io gets more than 1000 requests per day aggregate, so I think your original comment stands correct - thdoan 2016-09-15 16:05
@10basetom In a case I want to use if statement with the freegeoip.net option, such that if an item is empty, it shows NOT FOUND, how do I go about it - Afolabi Olaoluwa Akinwumi 2016-11-23 13:25
@AfolabiOlaoluwaAkinwumi you can try something like this: $.getJSON('//freegeoip.net/json/?callback=?', function(data) { if (!data || !data.ip) alert('IP not found'); }).fail(function() { alert('$.getJSON() request failed'); });thdoan 2016-11-24 09:52
Every single one of these use server-side code - John Weisz 2016-11-24 20:41
is there a way to get subnet mask as well - Muneeb Mirza 2017-01-27 04:20
@skobaljic Re. limitations usually meaning nothing: Good point, and perhaps a reason to stay away from the ones that need an api key, because usage of the key can be counted - Nick Rice 2017-05-04 09:36
@JohnWeisz True, but if the OP simply meant they could only update the page and not do anything server-side (unclear from question) then these options answer the question fine - Nick Rice 2017-05-04 09:43
You can also you https://ipfind.co/me It's a free service but sign up for a free API key to use the "/me" end point. Also supports HTTPS - JordanC 2017-07-15 07:52
@JordanC thanks, I'll add this to the list - thdoan 2017-07-16 07:45
This works perfectly while having ionic serve (on system ) but when i installed the application on device i am getting GET file://ipinfo.io/json net::ERRFILENOT_FOUND error - Shashank Shah 2017-09-07 08:44
@10basetom you can add http://www.stupidwebtools.com/api/my_ip.jso - Cœur 2017-09-18 13:07
@10basetom hi! checkout https://ipdata, we'd love to be added to this list. thank - Jonathan 2018-03-15 23:11
@Jonathan thanks, added - thdoan 2018-03-17 03:22
Which Ip it returns? My system Ip address is different and it is returning different value. How I can get the address of my system - Harsh Jaswal 2018-04-05 11:43
The Ublock Origin browser extension blocks Nekudo.

uBlock Origin has prevented the following page from loading:
https://geoip.nekudo.com/api/IP-address-removed-from-here
Because of the following filter
||geoip.nekudo.com^
Found in: EasyPrivacy
< - Rob Waa 2018-04-16 08:27
Maybe this one could be added : https://geoiplookup.io/api I don 't know how to find the limitations of the service though - Rob Waa 2018-04-16 09:32
Forgot. Example usage : https://json.geoiplookup.io/api https://json.geoiplookup.io/api/8.8.8.8 https://json.geoiplookup.io/api/adobe.co - Rob Waa 2018-04-16 09:41
@RobWaa thanks, I added the ad blocker limitation in the 4/14 update. I'll add geoiplookup.io shortly - thdoan 2018-04-17 00:49
@thdoan hey! thanks for adding us to the list. Our API has changed a bit in the last few weeks i.e. lots more data, would it be possible to update the example? Thanks - Jonathan 2018-05-01 10:46
@Jonathan updated. Thanks - thdoan 2018-05-09 04:33
@thdoan can you add https://ipgeolocation.io in the list? There is an endpoint which just returns IP address and does not require signup / api key. https://api.ipgeolocation.io/getip It has some intelligent filtering of results as well. Here is main geolocation endpoint 'https://api.ipgeolocation.io/ipgeo?ip=1.1.1.1&apiKey=API_KEY' You can read more about it on https://ipgeolocation.io/documentatio - Ejaz Ahmed 2018-06-11 19:38
@EjazAhmed added - thanks - thdoan 2018-06-12 01:24
@thdoan ipdata now requires API Keys. A free API Key can be gotten from ipdata.co/registration.htm - Jonathan 2018-10-11 17:16
@Jonathan thanks, updated - thdoan 2018-10-11 21:16
All of these answers rely on a third party service, which is a big drawback, not only because you depend on that service responding in a timely manner, but because if it does not and you don't set an appropiate timeout (which will always occur sonner than later), you will be delaying your page's load time, which is not good at all. So, why not just using your own server to return the client's IP?, which is BTW a trivial task with any programming language - Daniel J. 2018-12-03 16:37
@DanielJ.that's a good point if the question had been "how to get client's IP address using Node.js or similar server-side language" :-) - thdoan 2018-12-10 05:10


237

Update: I always wanted to make a min/ uglified version of the code, so here is an ES6 Promise code:

var findIP = new Promise(r=>{var w=window,a=new (w.RTCPeerConnection||w.mozRTCPeerConnection||w.webkitRTCPeerConnection)({iceServers:[]}),b=()=>{};a.createDataChannel("");a.createOffer(c=>a.setLocalDescription(c,b,b),b);a.onicecandidate=c=>{try{c.candidate.candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g).forEach(r)}catch(e){}}})

/*Usage example*/
findIP.then(ip => document.write('your ip: ', ip)).catch(e => console.error(e))

Note: This new minified code would return only single IP if you want all the IPs of the user( which might be more depending on his network), use the original code...


thanks to WebRTC, it is very easy to get local IP in WebRTC supported browsers( at least for now). I have modified the source code, reduced the lines, not making any stun requests since you only want Local IP, not the Public IP, the below code works in latest Firefox and Chrome, just run the snippet and check for yourself:

function findIP(onNewIP) { //  onNewIp - your listener function for new IPs
  var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
  var pc = new myPeerConnection({iceServers: []}),
    noop = function() {},
    localIPs = {},
    ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
    key;

  function ipIterate(ip) {
    if (!localIPs[ip]) onNewIP(ip);
    localIPs[ip] = true;
  }
  pc.createDataChannel(""); //create a bogus data channel
  pc.createOffer(function(sdp) {
    sdp.sdp.split('\n').forEach(function(line) {
      if (line.indexOf('candidate') < 0) return;
      line.match(ipRegex).forEach(ipIterate);
    });
    pc.setLocalDescription(sdp, noop, noop);
  }, noop); // create offer and set local description
  pc.onicecandidate = function(ice) { //listen for candidate events
    if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
    ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
  };
}



var ul = document.createElement('ul');
ul.textContent = 'Your IPs are: '
document.body.appendChild(ul);

function addIP(ip) {
  console.log('got ip: ', ip);
  var li = document.createElement('li');
  li.textContent = ip;
  ul.appendChild(li);
}

findIP(addIP);
<h1> Demo retrieving Client IP using WebRTC </h1>

what is happening here is, we are creating a dummy peer connection, and for the remote peer to contact us, we generally exchange ice candidates with each other. And reading the ice candidates( from local session description and onIceCandidateEvent) we can tell the IP of the user.

where I took code from --> Source

2015-09-29 10:03
by mido
I got "Error: RTCPeerConnection constructor passed invalid RTCConfiguration - malformed URI: undefined" in Firefox 2 - BeniBela 2015-11-24 13:37
@BeniBela updated code to work with firefox 26, checked in windows machine, can you check and confirm - mido 2015-11-25 01:11
Upvote because hands down best answer here, also thanks for the awesome GitHub repo - Kano 2016-05-16 10:49
Cool hack! Better than others advertising their remote services - Pawel 2016-09-09 15:22
With this I can get my inner-net IP address, that's awesome - rocky qi 2016-09-13 07:25
Does not work with com.android.chrome on Samsung mobile devices - mac address is returned - Dominic Cerisano 2016-09-24 00:28
Warning: This doesn't show your public IP, just the local network one. You can't use it for detecting a users country, for instance, if they are on a LA - FloatingRock 2016-11-23 08:20
@FloatingRock you can retrieve public IP as well, using STUN server (and configure it while creating the peer), then again, that would require you to maintain/ use a STUN server, bring server code into picture - mido 2016-11-23 11:00
This is known as the WebRTC Leak. Should be fixed by all mayor browsers, but it's not. More information here: https://www.privacytools.io/webrtc.html Possibly related to the Tor-browser leaking your real-ip - Kapitein Witbaard 2016-11-30 10:25
This is the 2017 answer for sure! Thanks - felipekm 2017-01-24 14:05
This shows my private address, not my public address - Rob Welan 2017-08-03 04:17
I think this solution does not work with Firefox anymore. (Tested with v56.0.2 (64-bit) - Below the Radar 2017-10-30 17:27
@mido, can you point to a working example of the STUN server you mentioned in your response to @FloatingRock - Highdown 2018-01-02 21:32
@mido Great lead, however, this code does not run on Safari ... any suggestions - Shlomi Schwartz 2018-12-23 14:43


177

You can, relaying it via server side with JSONP

And while googling to find one, found it here on SO Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

<script type="application/javascript">
    function getip(json){
      alert(json.ip); // alerts the ip address
    }
</script>

<script type="application/javascript" src="http://www.telize.com/jsonip?callback=getip"></script>

Note : The telize.com API has permanently shut down as of November 15th, 2015.

2009-05-01 07:02
by Chad Grant
while I appreciate this snippet, I think loading a JavaScript text content and evaluating that through a function is a severe security risk. What if the content of the response changes and all 100+ people here that voted this answer up and possibly used that snippet end up invoking a function with possible insecure content. I would only use this if it were a JSON string - auco 2013-11-25 15:26
`Error

Over Quota

This application is temporarily over its serving quota. Please try again later. - Brad M 2013-12-18 15:06

This is not a good answer as it involves a server side request. The question clearly stated "pure javascript" - Micah 2014-10-15 21:56
Micah, there is no way possible to get an ip address with pure javascript. I suggest you do some reading on NAT and how that works. You need a server to echo your internet IP address back to yo - Chad Grant 2014-10-17 00:54
"NetworkError: 404 Not Found - http://jsonip.appspot.com/?callback=getip - saravanabawa 2015-08-14 07:34
The service is now down - Cyril N. 2015-08-14 10:00
@CyrilN. yes, the creator of the service shut it down because it was being abused by spam/malware. see his post: http://www.cambus.net/adventures-in-running-a-free-public-api - nelsonic 2015-12-02 23:14
http://www.stupidwebtools.com/api/myip.txt or http://www.stupidwebtools.com/api/myip.json or http://www.stupidwebtools.com/api/my_ip.xm - Fabrizio 2015-12-27 22:32
This internet-based script is permanently non-fonctional now. Removing the dead code, it makes this answer a "you can Google to find something" answer. So it's not an answer anymore by Stack Overflow definition. Sorry @ChadGrant, but I suggest you delete it to give visibility to working answers - Cœur 2017-09-18 12:52


98

Most of the answers here "work around" the need for server-side code by... Hitting someone else's server. Which is a totally valid technique, unless you actually do need to get the IP address without hitting a server.

Traditionally this wasn't possible without some sort of a plugin (and even then, you'd likely get the wrong IP address if you were behind a NAT router), but with the advent of WebRTC it is actually possible to do this... If you're targeting browsers that support WebRTC (currently: Firefox, Chrome and Opera).

Please read mido's answer for details on how you can retrieve useful client IP addresses using WebRTC.

2008-12-24 18:25
by Shog9
I think you can: http://www.hashemian.com/tools/visitor-IP.ht - Oscar Mederos 2011-03-24 04:16
@oscar: that appears to be the same technique (JSONP-returned server-visible IP) that chad mentioned in his answer. Which doesn't match the OP's requirement of "no server-side code". But yes, that is one way to accomplish it if you ignore that requirement - Shog9 2011-03-24 04:40
This answer outdated because of WebRTC: http://stackoverflow.com/questions/20194722/can-you-get-a-users-local-lan-ip-address-via-javascrip - Akam 2016-02-11 10:32
Updated, @Akam. You should give mido some props for pointing this out a few months back (after YEARS of folks posting embarrassingly wrong answers that still required server support) - Shog9 2016-02-11 19:24


81

You can do an ajax call to hostip.info or a similar service...

function myIP() {
    if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
    else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.open("GET","http://api.hostip.info/get_html.php",false);
    xmlhttp.send();

    hostipInfo = xmlhttp.responseText.split("\n");

    for (i=0; hostipInfo.length >= i; i++) {
        ipAddress = hostipInfo[i].split(":");
        if ( ipAddress[0] == "IP" ) return ipAddress[1];
    }

    return false;
}

As a bonus, geolocalisation information is returned in the same call.

2011-03-08 22:21
by Malta
You can also get a JSON representation using http://api.hostip.info/get_json.php, then parse the JSON with the browser function, jQuery or Prototype - Brad Folkens 2012-04-26 17:44
is there any request limit on "http://api.hostip.info/get_html.php" ? where can I see this api detail - Navin Leon 2012-06-20 07:29
api details: http://www.hostip.info/use.htm - d.raev 2013-07-15 14:42
It returns the IP of the Network Firewall. not the actual client IP. Is there a way we can get the actual Client IP - Leela Addagulla 2015-04-30 19:39
api.hostip.info doesn't resolve - Ken Sharp 2016-02-18 15:32


73

Try this
$.get("http://ipinfo.io", function(response) {
    alert(response.ip);
}, "jsonp");

OR

$(document).ready(function () {
    $.getJSON("http://jsonip.com/?callback=?", function (data) {
        console.log(data);
        alert(data.ip);
    });
});

Fiddle

2013-11-13 12:06
by Sridhar R
this works $.get("http://ipinfo.io", function(response) { alert(response.ip); }, "jsonp"); but how do I store the value into a variable? it seems to disappear outside of this get request loo - Diana Castillo 2014-09-24 17:31
For a list of all free IP lookup services, you can refer to my answer for http://stackoverflow.com/questions/391979/get-client-ip-using-just-javascrip - thdoan 2016-02-01 04:55
How do I send this function to return the value of the ip - Neftali Acosta 2018-01-20 22:43


50

Look no further

Check out http://www.ipify.org/

According to them:

  • You can use it without limit (even if you're doing millions of requests per minute).
  • ipify is completely open source (check out the GitHub repository).

Here's a working JS example (instead of wondering why this answer has so few votes, try it yourself to see it in action):

<script>
function getIP(json) {
  alert("My public IP address is: " + json.ip);
}
</script>
<script src="https://api.ipify.org?format=jsonp&callback=getIP"></script>

Too lazy to copy/paste? I like it. Here's a demo

Too lazy to click? :O

Note: Turn off Adblock Plus / uBlock & co before running the demo .. otherwise, it just won't work.

I have nothing to do with the IPify team. I just think it's ridiculously cool that someone would provide such a service for the general good.

2015-01-14 05:28
by FloatingRock
Best part is that this comes from "https" whereas my calls to http IP helpers would get blocked because they are "not secure" - Tessa 2017-03-13 13:41


45

You can't. You'd have to ask a server.

2015-04-09 03:09
by SteveShaffer
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - Himanshu 2015-04-09 04:09
But it kinda does, right? I mean, if the answer is just "no, you can't" then I would argue this is a more correct answer than the currently upvoted "here, use this random appspot app," which seems like a dangerous answer to be at the top of the list - SteveShaffer 2015-04-13 15:14
IMO This is the correct answer and should be accepted. The question specifically says "no server side code. - matthewwithanm 2015-05-14 15:28
http://stackoverflow.com/questions/20194722/can-you-get-a-users-local-lan-ip-address-via-javascrip - Akam 2016-02-11 10:33
Could you please elaborate? All the answers suggest you make a request to another server, but how does that server gets the IP from request you make and why can't browser do it - protasovams 2017-07-05 09:15
@matthewwithanm I couldn't agree more. I was scrolling through all the answers to see if anyone had said exactly this - and was prepared to offer it as an answer myself. All the highly upvoted answers, while informative, all answer a different question. Quoting the question: "I need to somehow pull the client's IP address using pure JavaScript; no server side code, not even SSI." This answer is, factually, the correct answer. Browser-sandboxed Javascript cannot do this (regardless of NAT or proxies). The question should be changed if one of the other answers is to be accepted - wally 2017-08-07 11:01


25

You can use my service http://ipinfo.io for this, which will give you the client IP, hostname, geolocation information and network owner. Here's a simple example that logs the IP:

$.get("http://ipinfo.io", function(response) {
    console.log(response.ip);
}, "jsonp");

Here's a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details: http://jsfiddle.net/zK5FN/2/

2013-07-23 10:48
by Ben Dowling
To avoid the Mixed Content Policy issues, change http://ipinfo.io to //ipinfo.io or http - Samuel Elh 2018-04-29 16:53


19

Include this code in your page : <script type="text/javascript" src="http://l2.io/ip.js"></script>

more doc here

2012-06-16 13:56
by L2.IO
Hm. It looks interesting... Any limits they have - indapublic 2014-09-17 06:34
library offlin - riccardo.tasso 2018-08-23 07:29


16

I would say Chad and Malta has great answer. However, theirs are complicated. So I suggest this code that I found from ads by country plugin

<script>
<script language="javascript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="javascript">
mmjsCountryCode = geoip_country_code();
mmjsCountryName = geoip_country_name();

</script>

No ajax. Just plain javascripts. :D

If you go to http://j.maxmind.com/app/geoip.js you will see that it contains

function geoip_country_code() { return 'ID'; }
function geoip_country_name() { return 'Indonesia'; }
function geoip_city()         { return 'Jakarta'; }
function geoip_region()       { return '04'; }
function geoip_region_name()  { return 'Jakarta Raya'; }
function geoip_latitude()     { return '-6.1744'; }
function geoip_longitude()    { return '106.8294'; }
function geoip_postal_code()  { return ''; }
function geoip_area_code()    { return ''; }
function geoip_metro_code()   { return ''; }

It doesn't really answer the question yet because

http://j.maxmind.com/app/geoip.js doesn't contain the IP (although I bet it uses the IP to get the country).

But it's so easy to make a PhP script that pop something like

function visitorsIP()   { return '123.123.123.123'; }

Make that. Put on http://yourdomain.com/yourip.php.

Then do

<script language="javascript" src="http://yourdomain.com/yourip.php"></script>

The question specifically mention NOT to use third party script. There is no other way. Javascript cannot know your IP. But other servers that can be accessed through javascript can which work just as well with no issue.

2012-09-07 09:01
by user4951
loading a JavaScript from a remote server and invoking functions with unknown contents seems like a huge security risk to me (what if the function contents change?). I'd rather prefer parsing a JSON response - auco 2013-11-25 15:35
Error 404: Object not foun - trejder 2015-06-17 06:58
It's been a very long time., The answer is quite false actually. I didn't know javascript can't know the IP - user4951 2017-01-19 10:02
oh it's correct the function visitorsIP is not meant to be a php code. It's a javacript code generated by php cod - user4951 2017-01-19 10:03
you can just use your own server then to print a javascript code that assign visitors ip - user4951 2017-01-19 10:04


15

There are two interpretations to this question. Most folks interpreted "Client IP" to mean the Public IP Address that Web server's see outside the LAN and out on the Internet. This is not the IP address of the client computer in most cases, though

I needed the real IP address of the computer that is running the browser that is hosting my JavaScript software (which is almost always a local IP address on a LAN that is behind something that NAT layer).

Mido posted a FANTASTIC answer, above, that seems to be the only answer that really provided the IP address of the client.

Thanks for that, Mido!

However, the function presented runs asynchronously. I need to actually USE the IP address in my code, and with an asynchronous solution, I might try to use the IP address before it is retrieved/learned/stored. I had to be able to wait on the results to arrive before using them.

Here is a "Waitable" version of Mido's function. I hope it helps someone else:

function findIP(onNewIP) { //  onNewIp - your listener function for new IPs
    var promise = new Promise(function (resolve, reject) {
        try {
            var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
            var pc = new myPeerConnection({ iceServers: [] }),
                noop = function () { },
                localIPs = {},
                ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
                key;
            function ipIterate(ip) {
                if (!localIPs[ip]) onNewIP(ip);
                localIPs[ip] = true;
            }
            pc.createDataChannel(""); //create a bogus data channel
            pc.createOffer(function (sdp) {
                sdp.sdp.split('\n').forEach(function (line) {
                    if (line.indexOf('candidate') < 0) return;
                    line.match(ipRegex).forEach(ipIterate);
                });
                pc.setLocalDescription(sdp, noop, noop);
            }, noop); // create offer and set local description

            pc.onicecandidate = function (ice) { //listen for candidate events
                if (ice && ice.candidate && ice.candidate.candidate && ice.candidate.candidate.match(ipRegex)) {
                    ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
                }
                resolve("FindIPsDone");
                return;
            };
        }
        catch (ex) {
            reject(Error(ex));
        }
    });// New Promise(...{ ... });
    return promise;
};

//This is the callback that gets run for each IP address found
function foundNewIP(ip) {
    if (typeof window.ipAddress === 'undefined')
    {
        window.ipAddress = ip;
    }
    else
    {
        window.ipAddress += " - " + ip;
    }
}

//This is How to use the Waitable findIP function, and react to the
//results arriving
var ipWaitObject = findIP(foundNewIP);        // Puts found IP(s) in window.ipAddress
ipWaitObject.then(
    function (result) {
        alert ("IP(s) Found.  Result: '" + result + "'. You can use them now: " + window.ipAddress)
    },
    function (err) {
        alert ("IP(s) NOT Found.  FAILED!  " + err)
    }
);


 

   
<h1>Demo "Waitable" Client IP Retrieval using WebRTC </h1>

2016-04-13 22:40
by BRebey


14

With using Smart-IP.net Geo-IP API. For example, by using jQuery:

$(document).ready( function() {
    $.getJSON( "http://smart-ip.net/geoip-json?callback=?",
        function(data){
            alert( data.host);
        }
    );
});
2012-02-27 23:00
by Mikhus
"Service Temporary Unavailable" - Iago 2014-11-19 02:45
wrote a simple api [https://geoip.immanuel.co/myip] to get client ip address, ssl enabled and no limi - Immanuel 2018-01-14 06:45


13

There's an easier and free approach that won't ask your visitor for any permission.

It consists in submitting a very simple Ajax POST request to http://freegeoip.net/json. Once you receive your location information, in JSON, you react accordingly by updating the page or redirecting to a new one.

Here is how you submit your request for location information:

jQuery.ajax( { 
  url: '//freegeoip.net/json/', 
  type: 'POST', 
  dataType: 'jsonp',
  success: function(location) {
     console.log(location)
  }
} );
2015-12-03 11:50
by Jijo Paulose
It seems they have shutdown on July 1st 201 - Nithin P.H 2018-09-28 12:24


12

Well, I am digressing from the question, but I had a similar need today and though I couldn't find the ID from the client using Javascript, I did the following.

On the server side: -

<div style="display:none;visibility:hidden" id="uip"><%= Request.UserHostAddress %></div>

Using Javascript

var ip = $get("uip").innerHTML;

I am using ASP.Net Ajax, but you can use getElementById instead of $get().

What's happening is, I've got a hidden div element on the page with the user's IP rendered from the server. Than in Javascript I just load that value.

This might be helpful to some people with a similar requirement like yours (like me while I hadn't figure this out).

Cheers!

2009-01-04 12:07
by Cyril Gupta
-1: The OP specifically mentions "no server side code", yet you use some C# - Bruno Reis 2011-05-07 08:36
Javascript only.. - Calgary Libertarian 2013-10-07 21:33
Wouldn't it be better to just output <script>var uip='<%= Request.UserHostAddress %>';</script> - Chris Haines 2014-03-17 09:54
aside from using server side code, one should never use the DOM to store data. This is just bad all over. Hainesy has a better idea to just assign to JS var - coblr 2015-02-19 00:37


9

Not possible in general unless you use some kind of external service.

2008-12-24 18:25
by Eugene Lazutkin


9

Get your IP with jQuery

you can get your public IP address with one line of JS? There is a free service that offers this for you and a get request is all that you need to do:

   $.get('http://jsonip.com/', function(r){ console.log(r.ip); });

For the above snippet to work, your browser will have to support CORS (cross-origin request sharing). Otherwise a security exception would be thrown. In older browsers, you can use this version, which uses a JSON-P request:

   $.getJSON('http://jsonip.com/?callback=?', function(r){ console.log(r.ip); });
2014-03-11 06:38
by sri_bb


8

There isn't really a reliable way to get the client computer's IP address.

This goes through some of the possibilities. The code that uses Java will break if the user has multiple interfaces.

http://nanoagent.blogspot.com/2006/09/how-to-find-evaluate-remoteaddrclients.html

From looking at the other answers here it sounds like you may want to get the client's public IP address, which is probably the address of the router they're using to connect to the internet. A lot of the other answers here talk about that. I would recommend creating and hosting your own server side page for receiving the request and responding with the IP address instead of depending on someone else's service that may or may not continue to work.

2008-12-24 18:28
by Sarel Botha


8

Javascript / jQuery get Client's IP Address & Location (Country, City)

You only need to embed a tag with "src" link to the server. The server will return "codehelper_ip" as an Object / JSON, and you can use it right away.

// First, embed this script in your head or at bottom of the page.
<script language="Javascript" src="http://www.codehelper.io/api/ips/?js"></script>
// You can use it
<script language="Javascript">
    alert(codehelper_ip.IP);
    alert(codehelper_ip.Country);
</script>

More information at Javascript Detect Real IP Address Plus Country

If you are using jQUery, you can try:

console.log(codehelper_ip); 

It will show you more information about returned object.

If you want callback function, please try this:

// First, embed this script in your head or at bottom of the page.
<script language="Javascript" src="http://www.codehelper.io/api/ips/?callback=yourcallback"></script>
// You can use it
<script language="Javascript">
    function yourcallback(json) {
       alert(json.IP);
     }
</script>
2013-07-22 23:56
by Ken Le
don't use language attribute, use type="text/javascript" instead, more on MDNAlex K 2013-10-31 15:29
as @Alex already mentioned, language is deprecated and is used only in legacy code. Use 'type="text/javascript"' for maximum compatibility instead - Gautham C. 2014-05-09 17:28
just FYI - the type field is not needed for HTML5 (JS is the default). http://www.w3schools.com/tags/attscripttype.as - pmont 2014-09-05 00:22
Just in case you missed these other comments, you should use type instead of languag - Mike 2015-07-07 01:49


8

Appspot.com callback's service isn't available. ipinfo.io seems to be working.

I did an extra step and retrieved all geo info using AngularJS. (Thanks to Ricardo) Check it out.

<div ng-controller="geoCtrl">
  <p ng-bind="ip"></p>
  <p ng-bind="hostname"></p>
  <p ng-bind="loc"></p>
  <p ng-bind="org"></p>
  <p ng-bind="city"></p>
  <p ng-bind="region"></p>
  <p ng-bind="country"></p>
  <p ng-bind="phone"></p>
</div>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.angularjs.org/1.2.12/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.12/angular-route.min.js"></script>
<script>
'use strict';
var geo = angular.module('geo', [])
.controller('geoCtrl', ['$scope', '$http', function($scope, $http) {
  $http.jsonp('http://ipinfo.io/?callback=JSON_CALLBACK')
    .success(function(data) {
    $scope.ip = data.ip;
    $scope.hostname = data.hostname;
    $scope.loc = data.loc; //Latitude and Longitude
    $scope.org = data.org; //organization
    $scope.city = data.city;
    $scope.region = data.region; //state
    $scope.country = data.country;
    $scope.phone = data.phone; //city area code
  });
}]);
</script>

Working page here: http://www.orangecountyseomarketing.com/projects/_ip_angularjs.html

2014-02-12 00:06
by Yamenator


8

You can use the userinfo.io javascript library.

<script type="text/javascript" src="userinfo.0.0.1.min.js"></script>

UserInfo.getInfo(function(data) {
  alert(data.ip_address);
}, function(err) {
  // Do something with the error
});

You can also use requirejs to load the script.

It will give you the IP address of your visitor, as well as a few data on its location (country, city, etc.). It is based on maxmind geoip database.

Disclaimer: I wrote this library

2014-09-21 05:37
by Vincent Durmont


7

If you're including an file anways, you could do a simple ajax get:

function ip_callback() {
    $.get("ajax.getIp.php",function(data){ return data; }
}

And ajax.getIp.php would be this:

<?=$_SERVER['REMOTE_ADDR']?>
2013-11-13 12:06
by Martijn
I can't use ph - Kinjan Koradiya 2013-11-13 12:08


7

I really like api.ipify.org because it supports both HTTP and HTTPS.

Here are some examples of getting the IP using api.ipify.org using jQuery.

JSON Format over HTTPS

https://api.ipify.org?format=json

$.getJSON("https://api.ipify.org/?format=json", function(e) {
    alert(e.ip);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

JSON Format over HTTP

http://api.ipify.org?format=json

$.getJSON("http://api.ipify.org/?format=json", function(e) {
    alert(e.ip);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Text format over HTTPS

If you don't want it in JSON there is also a plaintext response over HTTPS

https://api.ipify.org

Text format over HTTP

And there is also a plaintext response over HTTP

http://api.ipify.org
2016-03-25 16:26
by Tim Penner


6

I'm going to offer a method that I use a lot when I want to store information in the html page, and want my javascript to read information without actually having to pass parameters to the javascript. This is especially useful when your script is referenced externally, rather than inline.

It doesn't meet the criterion of "no server side script", however. But if you can include server side scripting in your html, do this:

Make hidden label elements at the bottom of your html page, just above the end body tag.

Your label will look like this:

<label id="ip" class="hiddenlabel"><?php echo $_SERVER['REMOTE_ADDR']; ?></label>

Be sure to make a class called hiddenlabel and set the visibility:hidden so no one actually sees the label. You can store lots of things this way, in hidden labels.

Now, in your javascript, to retrieve the information stored in the label (in this case the client's ip address), you can do this:

var ip = document.getElementById("ip").innerHTML;

Now your variable "ip" equals the ip address. Now you can pass the ip to your API request.

* EDIT 2 YEARS LATER * Two minor refinements:

I routinely use this method, but call the label class="data", because, in fact, it is a way to store data. Class name "hiddenlabel" is kind of a stupid name.

The second modification is in the style sheet, instead of visibility:hidden:

.data{
    display:none;
}

...is the better way of doing it.

2012-07-09 14:34
by TARKUS
Don't store data in the DOM. Why would anyone suggest that, even 2 years later? If you can inject whatever into the HTML file, just inject that value into a JS variable like so. . At least then screen readers will miss it and no getElementById or $('#stupidname') required - coblr 2015-02-19 00:42
@fractalspawn , For the reason that you can't insert php code into a .js file. Didn't think of THAT, did you smarty pants! ; - TARKUS 2015-02-19 01:21
Well, you could if you did though I'm not sure why you would do that either. My point is that if PHP can insert anything into the HTML that it's rendering, the best practice would be to have it insert a value into a JS variable within an inline script tag, rather than into a DOM element that you would then have to parse out in order to use, and could potentially be read by screen readers unless you took extra measures to prevent it - coblr 2015-02-23 23:07
There is absolutely no good reason why you can't or shouldn't add data holding elements to the DOM, and there are plenty of good reasons for doing it. In fact, those reasons are in my answer, if you would care to read it again. It is reliable, easy to control, and especially useful when your javascript file occurs on a remote site. Speaking of remote script, your example of "javascript.php" is a horrible idea, and probably wouldn't work, anyway. Think in terms of remote scripts, such as DISQUS - TARKUS 2015-02-24 21:57
Stumbled on this question, and I had to support @fractalspawn here : You shouldn't store data in the DOM. Actually his snippet <script>var ip = '<?php echo $_SERVER['REMOTE_ADDR']; ?>';</script> works flawlessly and you can access the ip variable in javascript without even needing to go through the dom with a getElementByID call. And as he said, it's much better for screen readers (or even text rendering browsers - Benjamin C. 2015-05-25 20:42
@ Benjamin C. - Again another reader completely misses the problem that a Javascript file, especially a remotely hosted Javascript library file DOES NOT PROCESS SERVER SIDE CODE. The suggestion to use "javascript.php" is an absurdly crude hack. Some people say data should not be stored in the DOM, not one of them has really explained why not. In fact that, TABLE elements are data storage elements, as well as LABEL elements. The method I described works especially well for remotely hosted scripts and html objects. Try to think your answer through before downvoting a better answer - TARKUS 2015-05-25 22:29
@Gregory Lewis: seems we both are not understanding each others points. I will just agree to disagree. Happy Coding! : - coblr 2015-05-26 20:28
@fractalspawn - If I was writing a .js script, it would instantly invalidate your suggestion. Nobody here has really explained why <label><?php echo $_SERVER['remote_addr']; ?></label> isn't a good idea - TARKUS 2015-05-27 22:16
The way I see the original problem is that we are trying to get the IP from the server. Assuming that the dev wants to use this information in JS code; putting it in the DOM then hiding it is redundant. Using the DOM to store arbitrary data from the server for use in JS code is what is not favorable here. If you only wanted to display it to the user then your answer is fine (hiding styles excluded). Additionally, PHP doesn't care what/who you are echoing to. It could be .jpg data, .js code or .css rules. IIRC, as long as the browser gets what it expects, the source and means are of no concern - coblr 2015-05-28 23:05
To your other comment about why DOM data storage is bad.. well, you can still stop a car by gently hitting a wall at your destination, but there are better tools for the job now. We now know better and have great frameworks to alleviate this. I worked at a place where the DOM was just a huge config file for the JS, and it was a nightmare when restyled. If you feel that using