560

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.

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
FlySwat
  • 172,459
  • 74
  • 246
  • 311

31 Answers31

1145

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


Abstract

let apiKey = '1be9a6884abd4c3ea143b59ca317c6b2';
$.getJSON('https://ipgeolocation.abstractapi.com/v1/?api_key=' + apiKey, function(data) {
  console.log(JSON.stringify(data, null, 2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Limitations:

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

BigDataCloud

// Base
let apiKey = 'd9e53816d07345139c58d0ea733e3870';
$.getJSON('https://api.bigdatacloud.net/data/ip-geolocation?key=' + apiKey, function(data) {
  console.log(JSON.stringify(data, null, 2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

// Base + Confidence Area
let apiKey = 'd9e53816d07345139c58d0ea733e3870';
$.getJSON('https://api.bigdatacloud.net/data/ip-geolocation-with-confidence?key=' + apiKey, function(data) {
  console.log(JSON.stringify(data, null, 2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

// Base + Confidence Area + Hazard Report
let apiKey = 'd9e53816d07345139c58d0ea733e3870';
$.getJSON('https://api.bigdatacloud.net/data/ip-geolocation-full?key=' + apiKey, function(data) {
  console.log(JSON.stringify(data, null, 2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Limitations:

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

Cloudflare

$.get('https://www.cloudflare.com/cdn-cgi/trace', function(data) {
  // Convert key-value pairs to JSON
  // https://stackoverflow.com/a/39284735/452587
  data = data.trim().split('\n').reduce(function(obj, pair) {
    pair = pair.split('=');
    return obj[pair[0]] = pair[1], obj;
  }, {});
  console.log(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Limitations:

  • Returns plain text
  • Returns only IPv6 address if you have that

DB-IP

Try it: https://api.db-ip.com/v2/free/self

$.getJSON('https://api.db-ip.com/v2/free/self', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "ipAddress": "116.12.250.1",
  "continentCode": "AS",
  "continentName": "Asia",
  "countryCode": "SG",
  "countryName": "Singapore",
  "city": "Singapore (Queenstown Estate)"
}

Limitations:

  • 1,000 requests per day
  • Requires non-null Origin request header

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

GeoIPLookup.io

$.getJSON('https://json.geoiplookup.io/?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Limitations:

  • 10,000 requests per hour
  • Free plan only for non-commercial use
  • Returns only IPv6 address if you have that

geoPlugin

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

$.getJSON('http://www.geoplugin.net/json.gp', 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

$.get('https://api.hackertarget.com/geoip/?q=116.12.250.1', function(data) {
  // Convert key-value pairs to JSON
  // https://stackoverflow.com/a/39284735/452587
  data = data.trim().split('\n').reduce(function(obj, pair) {
    pair = pair.split(': ');
    return obj[pair[0]] = pair[1], obj;
  }, {});
  console.log(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Limitations:

  • 100 requests per day
  • Requires IP address parameter
  • Returns plain text

ipapi

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)
  • Requires non-null Origin request header
  • Returns only IPv6 address if you have that

IP-API

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

$.getJSON('http://ip-api.com/json', 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

let apiKey = 'be0f755b93290b4c100445d77533d291763a417c75524e95e07819ad';
$.getJSON('https://api.ipdata.co?api-key=' + apiKey, function(data) {
  console.log(JSON.stringify(data, null, 2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Limitations:

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

IP Find

let apiKey = '50e887ce-e3bb-4f00-a9b9-667597db5539';
$.getJSON('https://ipfind.co/me?auth=' + apiKey, function(data) {
  console.log(JSON.stringify(data, null, 2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Limitations:

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

ipgeolocation

let apiKey = 'f8e0b361e8f4405c94613ab534959fdf';
$.getJSON('https://api.ipgeolocation.io/ipgeo?apiKey=' + apiKey, function(data) {
  console.log(JSON.stringify(data, null, 2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Limitations:

  • 50,000 requests per month
  • Requires registration to get your API key
  • Returns only IPv6 address if you have that

ipify

$.getJSON('https://api.ipify.org?format=jsonp&callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Limitations:

  • None

IPInfoDB

let apiKey = '25864308b6a77fd90f8bf04b3021a48c1f2fb302a676dd3809054bc1b07f5b42';
$.getJSON('https://api.ipinfodb.com/v3/ip-city/?format=json&key=' + apiKey, function(data) {
  console.log(JSON.stringify(data, null, 2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Limitations:

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

ipinfo.io

$.getJSON('https://ipinfo.io/json', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Limitations:

  • 50,000 requests per month

ipregistry

$.getJSON('https://api.ipregistry.co/?key=tryout', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Limitations:

  • Free plan includes 100,000 requests
  • Requires registration to get your API key
  • Returns only IPv6 address if you have that

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": "தமிழ்"
      },
      {
        "code": "zh",
        "name": "Chinese",
        "native": "中文"
      }
    ],
    "country_flag": "http://assets.ipstack.com/flags/sg.svg",
    "country_flag_emoji": "",
    "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

$.getJSON('https://jsonip.com/', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Limitations:

  • Returns only IPv6 address if you have that

JSON Test

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

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

Returns:

{
  "ip": "116.12.250.1"
}

Limitations:

  • No SSL (https)
  • Returns only IPv6 address if you have that

Snoopi.io

let apiKey = 'ed5ebbeba257b8f262a6a9bbc0ec678e';
$.getJSON('https://api.snoopi.io/116.12.250.1?apikey=' + apiKey, function(data) {
  console.log(JSON.stringify(data, null, 2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Limitations:

  • 10,000 requests per month
  • 1 request every 2 seconds
  • Requires IP address parameter
  • Requires registration to get your API key

VANILLA JAVASCRIPT

With modern browsers, you can use the native Fetch API instead of relying on jQuery's $.getJSON(). Here's an example:

let apiKey = '1be9a6884abd4c3ea143b59ca317c6b2';
// Make the request
fetch('https://ipgeolocation.abstractapi.com/v1/?api_key=' + apiKey)
  // Extract JSON body content from HTTP response
  .then(response => response.json())
  // Do something with the JSON data
  .then(data => {
    console.log(JSON.stringify(data, null, 2))
  });

NOTES

  • Since these are all free services, 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 and stability.
  • As @skobaljic noted in the comments below, the request quotas are mostly academic since calls are happening client-side and most end users will never exceed their quota.
  • Some services don't have runnable snippets because they don't allow SSL connections in the free plan or require a non-null Origin request header (StackOverflow snippets are forced to use https and have Origin: null in the request headers).

UPDATES

  • 2/1/2016: Removed Telize (no longer offers free plan)
  • 4/18/2016: Removed freegeoip.net (out of service)
  • 4/26/2016: Added DB-IP
  • 4/26/2016: Added Hacker Target
  • 7/6/2016: Reinstated freegeoip.net
  • 7/6/2016: Removed ip-json.rhcloud.com (dead link)
  • 12/21/2016: Removed Hacker Target (out of service)
  • 2/10/2017: Added Nekudo
  • 4/20/2017: Added ipapi (thanks Ahmad Awais)
  • 4/24/2017: Reinstated Hacker Target
  • 4/24/2017: Removed Snoopi.io (out of service)
  • 7/16/2017: Added limitation "No SSL (https) with the free plan"
  • 7/16/2017: Added IP Find (thanks JordanC)
  • 9/25/2017: Added Stupid Web Tools (thanks Cœur)
  • 3/16/2018: Added ipdata (thanks Jonathan)
  • 4/14/2018: Renamed freegeoip.net to ipstack (thanks MA-Maddin)
  • 4/16/2018: Added GeoIPLookup.io (thanks Rob Waa)
  • 6/11/2018: Added ipgeolocation (thanks Ejaz Ahmed)
  • 7/31/2019: Added ipregistry (thanks Laurent)
  • 8/16/2019: Added SmartIP.io (thanks kevinj)
  • 8/22/2019: Removed Stupid Web Tools (out of service)
  • 12/10/2019: Added Cloudflare
  • 1/9/2020: Removed SmartIP.io (out of service)
  • 11/6/2020: Added Abstract
  • 11/13/2020: Added AstroIP.co
  • 4/13/2021: Replaced code samples with snippets (was getting close to 30k character limit)
  • 4/13/2021: Added code to convert key-value pairs to JSON for plain text responses
  • 4/13/2021: Added limitation "Requires non-null Origin request header"
  • 4/13/2021: Added BigDataCloud
  • 4/13/2021: Reinstated Snoopi.io
  • 4/13/2021: Removed AstroIP.co (out of service)
  • 4/13/2021: Removed Nekudo (now part of ipapi)
thdoan
  • 18,421
  • 1
  • 62
  • 57
312

UPDATE 2021:

As shown recently by a new Github repository, webrtc-ip, you can now leak a user's public IP address using WebRTC. Sadly, this leak does not work for private IPs, due to the gradual shift to mDNS (at least for WebRTC), completely explained here. However, here's a working demo:

getIPs().then(res => document.write(res.join('\n')))
<script src="https://cdn.jsdelivr.net/gh/joeymalvinni/webrtc-ip/dist/bundle.dev.js"></script>

The compiled source code for this repository can be found here.




(Previously) Final Update

This solution would not longer work because browsers are fixing webrtc leak: for more info on that read this other question: RTCIceCandidate no longer returning IP


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

divinelemon
  • 1,925
  • 2
  • 23
mido
  • 24,198
  • 15
  • 92
  • 117
  • I got "Error: RTCPeerConnection constructor passed invalid RTCConfiguration - malformed URI: undefined" in Firefox 26 – BeniBela Nov 24 '15 at 13:37
  • @BeniBela updated code to work with firefox 26, checked in windows machine, can you check and confirm? – mido Nov 25 '15 at 01:11
  • With this I can get my inner-net IP address, that's awesome! – rocky qi Sep 13 '16 at 07:25
  • Does not work with com.android.chrome on Samsung mobile devices - mac address is returned. – Dominic Cerisano Sep 24 '16 at 00:28
  • 35
    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 LAN – FloatingRock Nov 23 '16 at 08:20
  • 1
    @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 Nov 23 '16 at 11:00
  • 10
    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 Nov 30 '16 at 10:25
  • This shows my private address, not my public address. – Rob Welan Aug 03 '17 at 04:17
174

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.

Community
  • 1
  • 1
Chad Grant
  • 44,326
  • 9
  • 65
  • 80
  • 46
    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 Nov 25 '13 at 15:26
  • 33
    `Error Over Quota This application is temporarily over its serving quota. Please try again later.` – Brad M Dec 18 '13 at 15:06
  • 28
    This is not a good answer as it involves a server side request. The question clearly stated "pure javascript". – Micah Oct 15 '14 at 21:56
  • 3
    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 you – Chad Grant Oct 17 '14 at 00:54
  • 11
    The service is now down. – Cyril N. Aug 14 '15 at 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 Dec 02 '15 at 23:14
  • http://www.stupidwebtools.com/api/my_ip.txt or http://www.stupidwebtools.com/api/my_ip.json or http://www.stupidwebtools.com/api/my_ip.xml – Fabrizio Dec 27 '15 at 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 Sep 18 '17 at 12:52
113

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.

Community
  • 1
  • 1
Shog9
  • 156,901
  • 35
  • 231
  • 235
  • 24
    @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 Mar 24 '11 at 04:40
  • This answer outdated because of WebRTC: http://stackoverflow.com/questions/20194722/can-you-get-a-users-local-lan-ip-address-via-javascript – Akam Feb 11 '16 at 10:32
  • 1
    Updated, @Akam. You should [give mido some props](http://stackoverflow.com/questions/391979/get-client-ip-using-just-javascript/32841164#32841164) for pointing this out a few months back (after YEARS of folks posting embarrassingly wrong answers that still required server support). – Shog9 Feb 11 '16 at 19:24
  • is WebRTC more widely supported now?! – oldboy Jul 25 '19 at 20:22
  • 1
    According to that "CanIUse" link, it is, @BugWhisperer. Unless you need IE. – Shog9 Jul 25 '19 at 20:25
103

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.

FloatingRock
  • 6,741
  • 6
  • 42
  • 75
100

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

SteveShaffer
  • 1,577
  • 1
  • 10
  • 14
  • 49
    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 Apr 13 '15 at 15:14
  • 24
    IMO This is the correct answer and should be accepted. The question specifically says "no server side code." – matthewwithanm May 14 '15 at 15:28
  • http://stackoverflow.com/questions/20194722/can-you-get-a-users-local-lan-ip-address-via-javascript – Akam Feb 11 '16 at 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 Jul 05 '17 at 09:15
  • 3
    @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 Aug 07 '17 at 11:01
82

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.

inukshuk
  • 1,027
  • 7
  • 5
77
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

Sridhar R
  • 20,190
  • 6
  • 38
  • 35
  • 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 loop –  Sep 24 '14 at 17:31
  • 1
    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-javascript – thdoan Feb 01 '16 at 04:55
  • How do I send this function to return the value of the ip? – Neftali Acosta Jan 20 '18 at 22:43
27

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/

Ben Dowling
  • 17,187
  • 8
  • 87
  • 103
22

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

more doc here

Aliaksandr Sushkevich
  • 11,550
  • 7
  • 37
  • 44
L2.IO
  • 269
  • 2
  • 3
  • There is some degree of spammy pop ups associated with l2.io ref: https://www.hybrid-analysis.com/sample/c7f6ecfdd2e7cfb0dbd5c0151fac6547dbbc521bf2a6cd58324d19922d4bec70?environmentId=100 allows embedding of links like in the sample http://117.254.84.212:3000/getjs?nadipdata="{"url":"/ip.js?var=myip","host":"l2.io","referer":"http://website.com/?h=jn8bnnbgisbnnnhbn","categories":[0],"reputations":[1],"nadipdomain":1}"&screenheight=768&screenwidth=1366&tm=1557565256073&lib=true&fingerprint=c2VwLW5vLXJlZGlyZWN0 – Wayne DSouza May 11 '19 at 10:15
18

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>
BRebey
  • 671
  • 8
  • 12
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.

user4951
  • 32,206
  • 53
  • 172
  • 282
  • 9
    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 Nov 25 '13 at 15:35
  • 3
    Error 404: Object not found – trejder Jun 17 '15 at 06:58
  • 1
    It's been a very long time., The answer is quite false actually. I didn't know javascript can't know the IP. – user4951 Jan 19 '17 at 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 code – user4951 Jan 19 '17 at 10:03
  • you can just use your own server then to print a javascript code that assign visitors ip. – user4951 Jan 19 '17 at 10:04
16

First of all the actual answer: It is not possible to use purely client-side executed code to find out your own IP address.

However, you can just do a GET request towards https://hutils.loxal.net/whois and receive something like this to obtain a client's IP address

{
  "ip": "88.217.152.15",
  "city": "Munich",
  "isp": "M-net Telekommunikations GmbH",
  "country": "Germany",
  "countryIso": "DE",
  "postalCode": "80469",
  "subdivisionIso": "BY",
  "timeZone": "Europe/Berlin",
  "cityGeonameId": 2867714,
  "countryGeonameId": 2921044,
  "subdivisionGeonameId": 2951839,
  "ispId": 8767,
  "latitude": 48.1299,
  "longitude": 11.5732,
  "fingerprint": "61c5880ee234d66bded68be14c0f44236f024cc12efb6db56e4031795f5dc4c4",
  "session": "69c2c032a88fcd5e9d02d0dd6a5080e27d5aafc374a06e51a86fec101508dfd3",
  "fraud": 0.024,
  "tor": false
}
Alex
  • 8,245
  • 8
  • 46
  • 55
15

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

Eugene Lazutkin
  • 43,776
  • 8
  • 49
  • 56
  • 1
    Indeed, this is possible using Javascript by relying on a third-party service such as [Ipregistry](https://ipregistry.co) (disclaimer: I run the service): https://ipregistry.co/docs/getting-location-from-ip-address#javascript You can get the IP address, and much related information including threat data, all in a single call. – Laurent Sep 29 '19 at 15:06
14

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!

Cyril Gupta
  • 13,505
  • 11
  • 64
  • 87
  • 20
    -1: The OP specifically mentions "no server side code", yet you use some C#. – Bruno Reis May 07 '11 at 08:36
  • 8
    Wouldn't it be better to just output ``? – Chris Haines Mar 17 '14 at 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 Feb 19 '15 at 00:37
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)
  }
} );
Jijo Paulose
  • 1,896
  • 18
  • 20
13

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);
        }
    );
});
Mikhus
  • 1,069
  • 11
  • 8
11

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
Tim Penner
  • 3,551
  • 21
  • 36
10

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

Vincent Durmont
  • 813
  • 8
  • 16
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); });
srikanth_yarram
  • 957
  • 9
  • 16
9

Use ipdata.co.

The API also provides geolocation data and has 10 global endpoints each able to handle >800M requests a day!

This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.

$.get("https://api.ipdata.co?api-key=test", function (response) {
    $("#response").html(response.ip);
}, "jsonp");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="response"></pre>
Jonathan
  • 10,792
  • 5
  • 65
  • 85
8

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.

TARKUS
  • 2,170
  • 5
  • 34
  • 52
  • 3
    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 Feb 19 '15 at 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 Feb 19 '15 at 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 Feb 23 '15 at 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 Feb 24 '15 at 21:57
  • Stumbled on this question, and I had to support @fractalspawn here : You shouldn't store data in the DOM. Actually his snippet `` 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. May 25 '15 at 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 May 25 '15 at 22:29
  • @Gregory Lewis: seems we both are not understanding each others points. I will just agree to disagree. Happy Coding! :) – coblr May 26 '15 at 20:28
  • @fractalspawn - If I was writing a .js script, it would instantly invalidate your suggestion. Nobody here has really explained why `` isn't a good idea. – TARKUS May 27 '15 at 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 May 28 '15 at 23:05
  • 3
    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 – coblr May 28 '15 at 23:20
  • Yeah, I agree. I'm really glad I don't work with somebody who would consider writing a server side script like "javascript.php" as a reasonable solution to a client side scripting language, especially when we build script libraries that may reside on an altogether different domain :/ And I guess I'm still not seeing the disadvantage of using DOM elements to store data, especially in light of the fact that you don't always have the ability to write a "javascript.php" type javascript library. – TARKUS May 29 '15 at 02:07
  • @TARKUS He is putting that script in a html file... same as you do your label. Of course there is no good reason to put data in a html. Keep it simple in a js variable. – Totty.js Dec 15 '17 at 00:01
  • @Totty.js he's linking a php file, not a javascript file. What if it was cross domain? Has to be a .js file. – TARKUS Dec 16 '17 at 02:21
  • I mean this is better: `` than putting ``. No need to parse html in the first one as it is simple js. – Totty.js Dec 17 '17 at 16:27
  • @Totty.js read the question again. You're making the assumption that it's about linking to a remote script. That's not in the question at all. The OP wants to access the remote IP. That's all. – TARKUS Dec 18 '17 at 17:23
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>
Ken Le
  • 1,787
  • 2
  • 22
  • 34
  • 1
    don't use `language` attribute, use `type="text/javascript"` instead, more on [MDN](https://developer.mozilla.org/en/docs/Web/HTML/Element/script) – Alex K Oct 31 '13 at 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. May 09 '14 at 17:28
  • 1
    just FYI - the type field is not needed for HTML5 (JS is the default). http://www.w3schools.com/tags/att_script_type.asp – pmont Sep 05 '14 at 00:22
  • Just in case you missed these other comments, you should use type instead of language – Mike Jul 07 '15 at 01:49
8

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']?>
Martijn
  • 15,791
  • 4
  • 36
  • 68
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

Yamenator
  • 99
  • 1
  • 2
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.

Sarel Botha
  • 12,419
  • 7
  • 54
  • 59
8

Try this: http://httpbin.org/ip (or https://httpbin.org/ip)

Example with https:

$.getJSON('https://httpbin.org/ip', function(data) {
                console.log(data['origin']);
});

Source: http://httpbin.org/

SimC
  • 105
  • 2
  • 8
7

Get System Local IP:

  try {
var RTCPeerConnection = window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (RTCPeerConnection) (function () {
    var rtc = new RTCPeerConnection({ iceServers: [] });
    if (1 || window.mozRTCPeerConnection) {
        rtc.createDataChannel('', { reliable: false });
    };

    rtc.onicecandidate = function (evt) {
        if (evt.candidate) grepSDP("a=" + evt.candidate.candidate);
    };
    rtc.createOffer(function (offerDesc) {
        grepSDP(offerDesc.sdp);
        rtc.setLocalDescription(offerDesc);
    }, function (e) { console.warn("offer failed", e); });


    var addrs = Object.create(null);
    addrs["0.0.0.0"] = false;
    function updateDisplay(newAddr) {
        if (newAddr in addrs) return;
        else addrs[newAddr] = true;
        var displayAddrs = Object.keys(addrs).filter(function (k) { return addrs[k]; });
        LgIpDynAdd = displayAddrs.join(" or perhaps ") || "n/a";
        alert(LgIpDynAdd)
    }

    function grepSDP(sdp) {
        var hosts = [];
        sdp.split('\r\n').forEach(function (line) {
            if (~line.indexOf("a=candidate")) {
                var parts = line.split(' '),
                    addr = parts[4],
                    type = parts[7];
                if (type === 'host') updateDisplay(addr);
            } else if (~line.indexOf("c=")) {
                var parts = line.split(' '),
                    addr = parts[2];
                alert(addr);
            }
        });
    }
})();} catch (ex) { }
Mohan Kumar
  • 647
  • 7
  • 8
7

If you use NGINX somewhere, you can add this snippet and ask your own server via any AJAX tool.

location /get_ip {
    default_type text/plain;
    return 200 $remote_addr;
}
leitasat
  • 896
  • 3
  • 12
  • 14
3
<!DOCTYPE html>
<html ng-app="getIp">
<body>
    <div ng-controller="getIpCtrl">
        <div ng-bind="ip"></div>
    </div>

    <!-- Javascript for load faster
    ================================================== -->
    <script src="lib/jquery/jquery.js"></script>
    <script src="lib/angular/angular.min.js"></script>
    <script>
    /// Scripts app

    'use strict';

    /* App Module */
    var getIp = angular.module('getIp', [ ]);

    getIp.controller('getIpCtrl', ['$scope', '$http',
      function($scope, $http) {
        $http.jsonp('http://jsonip.appspot.com/?callback=JSON_CALLBACK')
            .success(function(data) {
            $scope.ip = data.ip;
        });
      }]);

    </script>
</body>
</html>
1

Java Script to find IP

To get the IP Address I am making a JSON call to the Free Web Service. like

[jsonip.com/json, ipinfo.io/json, www.telize.com/geoip, ip-api.com/json, api.hostip.info/get_json.php]

and I am passing the name of the callback function which will be called on completion of the request.

<script type="text/javascript">
    window.onload = function () {
    var webService = "http://www.telize.com/geoip";
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = webService+"?callback=MyIP";
        document.getElementsByTagName("head")[0].appendChild(script);
    };
    function MyIP(response) {
        document.getElementById("ipaddress").innerHTML = "Your IP Address is " + response.ip;
    }
</script>
<body>
    <form>
        <span id = "ipaddress"></span>
    </form>
</body>

for xml response code

WebRTC which doesn't require server support.

Community
  • 1
  • 1
Yash
  • 9,250
  • 2
  • 69
  • 74