如何使用JavaScript获取客户端的IP地址?

我需要以某种方式使用JavaScript检索客户端的IP地址; 没有服务器端代码,甚至没有SSI。

但是,我并不反对使用免费的第三方脚本/服务。

我会使用一个可以返回JSON的Web服务(与jQuery一起使事情变得更简单)。 以下是我可以找到的所有免费活动 IP查找服务以及它们返回的信息。 如果您知道更多,请添加评论,我将更新此答案。


DB-IP

试试看: http //api.db-ip.com/addrinfo?api_key = < 你的api密钥 >&addr = < ip address >

返回:

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

限制:

  • 每天2,500个请求
  • 不支持JSONP回调
  • 需要IP地址参数
  • 需要电子邮件地址才能获取API密钥
  • 没有SSL(https)与免费计划

Geobytes

试试看: http //gd.geobytes.com/GetCityDetails

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

返回:

 { "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" } 

限制:

  • 每小时16,384个请求
  • 没有SSL(https)与免费计划
  • 可以返回错误的位置(我在新加坡,而不是沙特阿拉伯)

GeoIPLookup.io

试试吧: https //json.geoiplookup.io/api

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

返回:

 { "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 } 

限制:

  • 未知

geoPlugin

试试看: http //www.geoplugin.net/json.gp

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

返回:

 { "geoplugin_request": "116.12.250.1", "geoplugin_status": 200, "geoplugin_credit": "Some of the returned data includes GeoLite data created by MaxMind, available from http://www.maxmind.com.", "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": "$", "geoplugin_currencySymbol_UTF8": "$", "geoplugin_currencyConverter": 1.4239 } 

限制:

  • 每分钟120个请求
  • 没有SSL(https)与免费计划

黑客目标

试试看: https //api.hackertarget.com/geoip/?q = < ip address >

返回:

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

限制:

  • 每天50个请求
  • 不支持JSONP回调
  • 需要IP地址参数
  • 返回纯文本

ipapi.co

试试看: https //ipapi.co/json/

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

返回:

 { "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" } 

限制:

  • 每天1,000个请求
  • 需要SSL(https)

IP-API.com

试试吧: http //ip-api.com/json

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

返回:

 { "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": "" } 

限制:

  • 每分钟150个请求
  • 没有SSL(https)与免费计划

Ipdata.co

试试吧: https //api.ipdata.co

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

返回:

 { "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": "http://sofzh.miximages.com/javascript/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 } } 

限制:

  • 每天1,500个请求
  • 需要电子邮件地址才能获取API密钥
  • 需要SSL(https)

IP查找

试试看: https //ipfind.co/me? auuth = < 你的api密钥 >

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

返回:

 { "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" ] } 

限制:

  • 每天300个请求
  • 需要注册才能获得API密钥

IPGeolocation的

试试吧: https //api.ipgeolocation.io/ipgeo? apiKey = < 你的api密钥 >

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

返回:

 { "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": "http://sofzh.miximages.com/javascript/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" } } 

限制:

  • 每月50,000个请求
  • 需要注册才能获得API密钥

ipify

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

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

返回:

 { "ip": "116.12.250.1" } 

限制:

  • 没有

IPInfoDB

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

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

返回:

 { "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" } 

限制:

  • 每秒两个请求
  • 需要注册才能获得API密钥

ipinfo.io

试试看: https //ipinfo.io/json

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

返回:

 { "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" } 

限制:

  • 每天1,000个请求

ipstack (原freegeoip.net)

试试看: http //api.ipstack.com/ < ip address >?access_key = <你的api密钥>

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

返回:

 { "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 } } 

限制:

  • 每月10,000个请求
  • 需要IP地址参数
  • 需要注册才能获得API密钥
  • 没有SSL(https)与免费计划

jsonip.com

试试吧: https //jsonip.com

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

返回:

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

限制:

  • 回应包括追加销售和政治

JSON测试

试试吧: http //ip.jsontest.com/

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

返回:

 { "ip": "116.12.250.1" } 

限制:

  • 没有SSL(https)
  • 经常下降(超过配额),因此我不会将其用于生产
  • 如果您有IPv6地址,则返回IPv6地址,这可能不是您想要的

Nekudo

试试看: https //geoip.nekudo.com/api

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

返回:

 { "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" } 

限制:

  • 使用EasyPrivacy列表阻止广告拦截器

愚蠢的Web工具

试试看: 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)); }); 

返回:

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

限制:

  • 没有SSL(https)

请记住,由于这些都是免费服务,您的里程可能会因超出配额和正常运行时间而有所不同,并且谁知道他们何时/是否会在路上脱机(图A: Telize )。 如果您需要更多function(如SSL支持),这些服务中的大多数还提供付费层。

另外,正如skobaljic在下面的评论中指出的那样,请求配额主要是学术性的,因为这是在客户端发生的,大多数最终用户永远不会超过配额。

更新

  • 2016年2月1日:删除Telize (不再提供免费计划)
  • 2016年4月18日:删除了freegeoip.net (停止服务)
  • 2016年4月26日:添加了DB-IP
  • 2016年4月26日:添加了黑客目标
  • 2016年7月6日:恢复了freegeoip.net
  • 2016年7月6日:删除了ip-json.rhcloud.com (死链接)
  • 2016年12月21日:删除黑客目标 (停止服务)
  • 2017/10/10 :添加了Nekudo
  • 2017年4月20日:添加了ipapi.co (感谢Ahmad Awais)
  • 4/24/2017:恢复黑客目标
  • 4/24/2017:删除了Snoopi.io (停止服务)
  • 7/16/2017:添加IP查找 (感谢JordanC)
  • 7/16/2017:更新了不支持SSL的免费计划的限制
  • 9/25/2017:添加了愚蠢的Web工具 (感谢Cœur)
  • 3/16/2018 :添加了Ipdata.co (感谢Jonathan)
  • 4/14/2018:将freegeoip.net重命名为ipstack (感谢MA-Maddin)
  • 4/16/2018:添加了GeoIPLookup.io (感谢Rob Waa)
  • 6/11/2018:添加了ipgeolocation (感谢Ejaz Ahmed)

更新 :我一直想制作一个min / uglified版本的代码,所以这是一个ES6 Promise代码:

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

您可以通过服务器端使用JSONP进行转发

在谷歌搜索找到一个,在这里找到它我可以使用客户端Javascript执行DNS查找(IP地址的主机名)?

   

注意:截至2015年11月15日, telize.com API已永久关闭 。

这里的大多数答案“解决”服务器端代码的需求…击中别人的服务器。 这是一种完全有效的技术,除非您确实需要获取IP地址而不需要服务器。

传统上,如果没有某种插件,这是不可能的(即使这样,如果你在NAT路由器后面,你可能会得到错误的 IP地址),但随着WebRTC的出现,它实际上可以做到这一点。 如果你的目标是支持WebRTC的浏览器 (目前是:Firefox,Chrome和Opera)。

有关如何使用WebRTC检索有用的客户端IP地址的详细信息, 请阅读mido的答案

你可以对hostip.info或类似的服务进行ajax调用……

 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; } 

作为奖励,地理定位信息在同一通话中返回。

试试这个

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

要么

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

小提琴

不要再犹豫了

查看http://www.ipify.org/

根据他们:

  • 您可以无限制地使用它(即使您每分钟执行数百万次请求)。
  • ipify是完全开源的(查看GitHub存储库 )。

这是一个有效的JS示例(而不是想知道为什么这个答案的票数很少,请亲自尝试看看它的实际效果):

   

太懒了复制/粘贴? 我喜欢。 这是一个💻演示

太懒了点击? :O

注意在运行演示之前关闭Adblock Plus / uBlock&co ..否则,它将无法正常工作。

我与IPify团队无关 。 我认为有人会为一般商品提供这样的服务真是太酷了。

你不能。 你必须问一个服务器。

您可以使用我的服务http://ipinfo.io ,它将为您提供客户端IP,主机名,地理位置信息和网络所有者。 这是一个记录IP的简单示例:

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

这是一个更详细的JSFiddle示例,它还打印出完整的响应信息,因此您可以看到所有可用的详细信息: http : //jsfiddle.net/zK5FN/2/

在您的页面中包含此代码:

更多doc 在这里

我想说乍得和马耳他有很好的答案。 然而,他们很复杂。 所以我建议通过国家/地区插件从广告中找到此代码

   

没有ajax。 只是简单的javascripts。 :d

如果你去http://j.maxmind.com/app/geoip.js,你会看到它包含

 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 ''; } 

它还没有真正回答这个问题,因为

http://j.maxmind.com/app/geoip.js不包含IP(虽然我打赌它使用IP来获取国家)。

但是制作一个像PhP这样的PhP脚本是如此容易

 function visitorsIP() { return '123.123.123.123'; } 

做那个。 穿上http://yourdomain.com/yourip.php 。

然后做

  

问题特别提到不要使用第三方脚本。 没有其他办法。 Javascript无法知道您的IP。 但是其他可以通过javascript访问的服务器可以正常工作而没有问题。

使用Smart-IP.net Geo-IP API 。 例如,通过使用jQuery:

 $(document).ready( function() { $.getJSON( "http://smart-ip.net/geoip-json?callback=?", function(data){ alert( data.host); } ); }); 

这个问题有两种解释。 大多数人将“客户端IP”解释为Web服务器在LAN外部和Internet上看到的公共IP地址。 但是,在大多数情况下,这不是客户端计算机的IP地址

我需要运行托管我的JavaScript软件的浏览器的计算机的真实IP地址(这几乎总是局域网上的本地IP地址,这是NAT层的背后)。

Mido在上面发布了一个奇妙的答案,这似乎是真正提供客户端IP地址的唯一答案。

谢谢你,Mido!

但是,所呈现的function是异步运行的。 我需要在我的代码中实际使用IP地址,并且使用异步解决方案,我可能会在检索/学习/存储之前尝试使用IP地址。 在使用它们之前,我必须能够等待结果到达。

这是Midofunction的“Waitable”版本。 我希望它可以帮助别人:

 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) } ); 
 

Demo "Waitable" Client IP Retrieval using WebRTC

有一种更简单,更自由的方法,不会要求访问者获得任何许可。

它包括向http://freegeoip.net/json提交一个非常简单的Ajax POST请求。 收到位置信息后,在JSON中,您会通过更新页面或重定向到新页面来做出相应的反应。

以下是您提交位置信息请求的方式:

 jQuery.ajax( { url: '//freegeoip.net/json/', type: 'POST', dataType: 'jsonp', success: function(location) { console.log(location) } } ); 

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

  

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).

干杯!

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

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); }); 

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.

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.  // You can use it  

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.  // You can use it  

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.

 

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

You can use the userinfo.io javascript library.

  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

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:

  

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:

  

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.

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"); 
  

You could do this entirely client side and mostly in JavaScript by using a Flash object that the js can call. Flash can access the IP address of the local machine which might not be very useful.

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); }); 
  
    
 var call_to = "http://smart-ip.net/geoip-json?callback=?"; $.getJSON(call_to, function(data){ alert(data.host); }); 

data.host is the ip address. Simply call this from your browser.

http://smart-ip.net/geoip-json?callback=? [Without quotes] and get the ip.

You can use web services like: http://ip-api.com/

例:

  additional example: http://whatmyip.info 
  $.getJSON("http://jsonip.com?callback=?", function (data) { alert("Your ip address: " + data.ip); });