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

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

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


#1楼

在您的页面中包含以下代码: <script type="text/javascript" src="http://l2.io/ip.js"></script>

更多文档在这里


#2楼

我将提供一种方法,当我想在html页面中存储信息时,我会使用很多方法,并且希望我的javascript读取信息而无需实际将参数传递给javascript。 当您的脚本是外部引用而不是内联引用时,这特别有用。

但是,它不符合“没有服务器端脚本”的标准。 但是,如果您可以在HTML中包含服务器端脚本,请执行以下操作:

在html页面底部的end body标签上方制作隐藏的标签元素。

您的标签将如下所示:

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

确保创建一个名为hiddenlabel的类并设置hiddenlabel visibility:hidden这样实际上没有人看到该标签。 您可以通过这种方式在隐藏标签中存储很多东西。

现在,在您的JavaScript中,要检索存储在标签中的信息(在本例中为客户端的IP地址),可以执行以下操作:

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

现在,您的变量“ ip”等于IP地址。 现在,您可以将ip传递给您的API请求。

*编辑2年后*两个小改进:

我通常使用此方法,但是将其称为标签class="data" ,因为实际上,这是一种存储数据的方法。 类名“ hiddenlabel”是一种愚蠢的名字。

第二个修改是在样式表中,而不是visibility:hidden

.data{
    display:none;
}

...是更好的方法


#3楼

我想说乍得和马耳他有很好的答案。 但是,它们很复杂。 因此,我建议我根据国家/地区插件从广告中找到的这段代码

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

没有阿贾克斯 只是普通的javascript。 :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脚本非常容易

function visitorsIP()   { return '123.123.123.123'; }

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

然后做

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

这个问题专门提到不要使用第三方脚本。 没有别的办法了。 Javascript无法识别您的IP。 但是可以通过javascript访问的其他服务器也可以正常工作。


#4楼

Javascript / jQuery获取客户的IP地址和位置 (国家/地区,城市)

您只需要将带有“ src”链接的标签嵌入服务器。 服务器将返回“ codehelper_ip”作为对象/ JSON,您可以立即使用它。

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

有关更多信息,请参见Javascript Detect Real IP Address Plus Country

如果您使用的是jQUery,则可以尝试:

console.log(codehelper_ip); 

它将向您显示有关返回对象的更多信息。

如果您想要回调函数,请尝试以下操作:

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

#5楼

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

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

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


#6楼

尝试这个
$.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);
    });
});

小提琴


#7楼

如果不包含文件,则可以执行一个简单的ajax get:

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

ajax.getIp.php将是这样的:

<?=$_SERVER['REMOTE_ADDR']?>

#8楼

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

#9楼

Appspot.com回调的服务不可用。 ipinfo.io似乎正在运行。

我做了一个额外的步骤,并使用AngularJS检索了所有地理信息。 (感谢里卡多)看看。

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

此处的工作页面: http : //www.orangecountyseomarketing.com/projects/_ip_angularjs.html


#10楼

var call_to = "http://smart-ip.net/geoip-json?callback=?";

$.getJSON(call_to, function(data){
   alert(data.host);
});

data.host是IP地址。 只需从浏览器调用即可。

http://smart-ip.net/geoip-json?callback=? [无引号]并获取IP。


#11楼

使用jQuery获取IP

您可以使用一行JS获得您的公共IP地址? 有一项免费服务可以为您提供此服务,并且您需要做的就是获取请求:

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

为了使以上代码段起作用,您的浏览器将必须支持CORS(跨域请求共享)。 否则会引发安全异常。 在较旧的浏览器中,可以使用此版本,该版本使用JSON-P请求:

   $.getJSON('http://jsonip.com/?callback=?', function(r){ console.log(r.ip); });

#12楼

您可以使用以下Web服务: http//ip-api.com/

例:

<script type="text/javascript" src="http://ip-api.com/json/?callback=foo">
<script>
    function foo(json) {
        alert(json.query)
    }
</script>

additional example: http://whatmyip.info    

#13楼

您可以使用客户端可以调用的Flash对象完全在客户端执行此操作,并且大多数情况下可以在JavaScript中执行此操作。 Flash 可以访问本地计算机的IP地址,该地址可能不是很有用。


#14楼

您可以使用userinfo.io javascript库。

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

您还可以使用requirejs加载脚本。

它会为您提供访问者的IP地址,以及有关其位置(国家,城市等)的一些数据。 它基于maxmind geoip数据库。

免责声明:我写了这个库


#15楼

别再看了

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

根据他们:

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

这是一个有效的JS示例(而不是想知道为什么这个答案投票这么少,请自己尝试一下以查看实际效果):

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

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

懒得点击? :O

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

我与IPify团队无关 。 我只是认为有人为一般利益提供这样的服务真是太荒谬了。


#16楼

你不能 您必须询问服务器。


#17楼

最终更新

此解决方案将不再起作用,因为浏览器正在修复webrtc泄漏:有关该问题的更多信息,请阅读另一个问题: RTCIceCandidate不再返回IP


更新 :我一直想做一个最小/丑陋的代码版本,所以这是一个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)) 

注意:如果您希望用户的所有IP(取决于用户网络的更多IP),请使用原始代码,这个新的压缩代码将仅返回单个IP ...


多亏了WebRTC ,在支持WebRTC的浏览器中很容易获得本地IP(至少现在如此)。 我已经修改了源代码,减少了行数,没有发出任何眩晕请求,因为您只需要本地IP,而不是公共IP,下面的代码在最新的Firefox和Chrome中有效,只需运行代码段并检查一下即可:

 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> 

这里发生的是,我们正在创建一个虚拟对等连接,并且为了使远程对等体与我们联系,我们通常会相互交换ice候选对象。 并从本地会话描述和onIceCandidateEvent中读取ice候选对象,我们可以告诉用户IP。

我从-> 代码获取代码的地方


#18楼

有一种更简单,免费的方法,它不会要求您的访客获得任何许可。

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

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

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

#19楼

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


数据库IP

尝试一下: http : //api.db-ip.com/addrinfo?api_key= < 您的api密钥 >&addr = < IP地址 >

返回值:

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

局限性:

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

千兆字节

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

局限性:

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

黑客目标

尝试一下: https : //api.hackertarget.com/geoip/?q= < IP地址 >

返回值:

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

局限性:

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

IP查找

尝试: https : //ipfind.co/me? auth = < 您的api密钥 >

$.getJSON('https://ipfind.co/me?auth=<your_api_key>', 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=<your_api_key>', 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": "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"
  }
}

局限性:

  • 每月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"
}

局限性:

  • 没有

IP信息数据库

尝试: https : //api.ipinfodb.com/v3/ip-city/?key = < 您的api密钥 >&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));
});

返回值:

{
  "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个请求

帝国主义

尝试: https : //api.ipregistry.co/?key = < 您的api密钥 >

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

返回值:

{
  "ip" : "116.12.250.1",
  "type" : "IPv4",
  "hostname" : null,
  "carrier" : {
    "name" : null,
    "mcc" : null,
    "mnc" : null
  },
  "connection" : {
    "asn" : 3758,
    "domain" : "singnet.com.sg",
    "organization" : "SingNet Pte Ltd",
    "type" : "isp"
  },
  "currency" : {
    "code" : "SGD",
    "name" : "Singapore Dollar",
    "plural" : "Singapore dollars",
    "symbol" : "SGD",
    "symbol_native" : "SGD",
    "format" : {
      "negative" : {
        "prefix" : "-SGD",
        "suffix" : ""
      },
      "positive" : {
        "prefix" : "SGD",
        "suffix" : ""
      }
    }
  },
  "location" : {
    "continent" : {
      "code" : "AS",
      "name" : "Asia"
    },
    "country" : {
      "area" : 692.0,
      "borders" : [ ],
      "calling_code" : "65",
      "capital" : "Singapore",
      "code" : "SG",
      "name" : "Singapore",
      "population" : 5638676,
      "population_density" : 8148.38,
      "flag" : {
        "emoji" : "🇸🇬",
        "emoji_unicode" : "U+1F1F8 U+1F1EC",
        "emojitwo" : "https://cdn.ipregistry.co/flags/emojitwo/sg.svg",
        "noto" : "https://cdn.ipregistry.co/flags/noto/sg.png",
        "twemoji" : "https://cdn.ipregistry.co/flags/twemoji/sg.svg",
        "wikimedia" : "https://cdn.ipregistry.co/flags/wikimedia/sg.svg"
      },
      "languages" : [ {
        "code" : "cmn",
        "name" : "cmn",
        "native" : "cmn"
      }, {
        "code" : "en",
        "name" : "English",
        "native" : "English"
      }, {
        "code" : "ms",
        "name" : "Malay",
        "native" : "Melayu"
      }, {
        "code" : "ta",
        "name" : "Tamil",
        "native" : "தமிழ்"
      }, {
        "code" : "zh",
        "name" : "Chinese",
        "native" : "中文"
      } ],
      "tld" : ".sg"
    },
    "region" : {
      "code" : null,
      "name" : "Singapore"
    },
    "city" : "Singapore",
    "postal" : "96534",
    "latitude" : 1.28967,
    "longitude" : 103.85007,
    "language" : {
      "code" : "cmn",
      "name" : "cmn",
      "native" : "cmn"
    },
    "in_eu" : false
  },
  "security" : {
    "is_bogon" : false,
    "is_cloud_provider" : false,
    "is_tor" : false,
    "is_tor_exit" : false,
    "is_proxy" : false,
    "is_anonymous" : false,
    "is_abuser" : false,
    "is_attacker" : false,
    "is_threat" : false
  },
  "time_zone" : {
    "id" : "Asia/Singapore",
    "abbreviation" : "SGT",
    "current_time" : "2019-09-29T23:13:32+08:00",
    "name" : "Singapore Standard Time",
    "offset" : 28800,
    "in_daylight_saving" : false
  }
}

局限性:

  • 免费计划包括100,000个请求
  • 需要注册才能获取您的API密钥

ipstack (以前是freegeoip.net)

尝试: http : //api.ipstack.com/ < IP地址 >?access_key = <您的api密钥>

$.getJSON('http://api.ipstack.com/<ip_address>?access_key=<your_api_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地址,该地址可能不是您想要的

udo堂

试试看: 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列表被广告阻止者阻止

智能IP

尝试: https : //api.smartip.io/? api_key = < 您的api密钥 >

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

返回值:

{
  "status-code": 200,
  "country": {
    "is-metric": true,
    "is-in-europe": false,
    "region-geo-id": null,
    "continent-geo-id": 6255147,
    "country-geo-id": 1880251,
    "region-code": null,
    "region-name": null,
    "continent-code": "AS",
    "continent-name": "Asia",
    "capital": "Singapur",
    "country-name": "Singapore",
    "country-two-letter-iso-code": "SG",
    "country-iso-code": "SG"
  },
  "location": {
    "metro-code": null,
    "longitude": 103.8547,
    "latitude": 1.2929,
    "timezone": "Asia/Singapore",
    "zip-code": null,
    "city": "Singapore"
  },
  "asn": {
    "organization": "SingNet",
    "asn": "AS3758"
  },
  "currency": {
    "native-name": "新币",
    "code": "SGD",
    "name": "Singapore Dollar",
    "symbol": "$"
  },
  "timezone": {
    "is-daylight-saving": false,
    "gmt-offset": 28800,
    "date-time": "2019-08-23T14:22:11+08:00",
    "microsoft-name": "Singapore Standard Time",
    "iana-name": "Asia/Singapore"
  },
  "security": {
    "is-crawler": false,
    "is-proxy": false,
    "is-tor": false,
    "tor-insights": null,
    "proxy-insights": null,
    "crawler-insights": null
  },
  "crypto": {
    "is-crypto-node": false,
    "crypto-insights": null
  },
  "user-agent": {
    "os": {
      "name": "Windows",
      "platform": "x64",
      "version": "10",
      "family": "Windows"
    },
    "device": {
      "brand": "",
      "model": "",
      "family": "desktop"
    },
    "engine-version": "",
    "engine": "Blink",
    "name": "Chrome",
    "type": "browser",
    "header": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36",
    "version": "76.0.3809.100",
    "family": "Chrome"
  },
  "error": null,
  "hostname": "116.12.250.1",
  "ip-type": "ipv4",
  "ip": "116.12.250.1"
}

局限性:

  • 每月250,000个请求
  • 需要注册才能获取您的API密钥
  • 需要SSL(https)

请记住,由于这些都是免费服务,因此您的里程数可能会超出配额和正常运行时间,并且谁知道何时/是否将它们离线离线(图A: Telize )。 如果您想要更多功能(例如SSL支持),这些服务中的大多数还提供付费层。

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

更新


#20楼

我真的很喜欢api.ipify.org因为它同时支持HTTP和HTTPS。

以下是一些使用jQuery的api.ipify.org获取IP的示例。

通过HTTPS的JSON格式

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> 

通过HTTP的JSON格式

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> 

通过HTTPS的文本格式

如果您不希望在JSON中使用它,那么还会通过HTTPS提供纯文本响应

https://api.ipify.org

通过HTTP的文本格式

还有一个通过HTTP的明文响应

http://api.ipify.org

#21楼

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

我需要运行浏览器的计算机的真实IP地址,该浏览器托管着我的JavaScript软件(几乎始终是NAT层后面的LAN上的本地IP地址)。

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

谢谢你,美度!

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

这是Mido功能的“等待”版本。 我希望它可以帮助其他人:

 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> 


#22楼

这里的大多数答案都是通过...攻击他人的服务器来“解决”对服务器端代码的需求。 除非您确实需要在不访问服务器的情况下获取IP地址,否则这是一种完全有效的技术。

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

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


#23楼

通常,除非您使用某种外部服务,否则不可能。


#24楼

确实没有可靠的方法来获取客户端计算机的IP地址。

这经历了一些可能性。 如果用户具有多个接口,则使用Java的代码将中断。

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

通过查看此处的其他答案,听起来您可能想要获取客户端的公共IP地址,该地址可能是他们用来连接到Internet的路由器的地址。 这里的许多其他答案都在谈论这一点。 我建议创建并托管自己的服务器端页面,以接收请求并使用IP地址进行响应,而不是依赖于可能会或可能不会继续工作的其他人的服务。


#25楼

好吧,我偏离了这个问题,但是今天我有类似的需求,尽管我无法使用Javascript从客户端中找到ID,但是我做了以下工作。

在服务器端:-

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

使用JavaScript

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

我正在使用ASP.Net Ajax,但是可以使用getElementById代替$ get()。

发生的是,我在页面上隐藏了div元素,并从服务器呈现了用户的IP。 比起Java,我只是加载了那个值。

这可能对像您这样有类似要求的人(像我一样,但我还没有弄清楚)有帮助。

干杯!


#26楼

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

#27楼

使用ipdata.co

该API还提供地理位置数据,并具有10个全局端点,每个端点每天可以处理超过800M个请求!

此答案使用的“测试” API密钥非常有限,仅用于测试几个调用。 注册您自己的免费API密钥,每天最多可获得1500个开发请求。

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


#28楼

试试这个: http : //httpbin.org/ip (或https://httpbin.org/ip

https的示例:

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

资料来源: http : //httpbin.org/


#29楼

首先是实际答案不可能仅使用客户端执行的代码来找到您自己的IP地址。

但是,您只需对https://api.muctool.de/whois进行GET并收到类似获取客户端IP地址的信息

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

#30楼

您可以对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;
}

另外,地理定位信息会在同一调用中返回。


#31楼

您可以通过JSONP通过服务器端进行中继

在搜寻时找到它的同时,在SO中找到了它。 我可以使用客户端Javascript执行DNS查找(从主机名到IP地址)吗?

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

注意: telize.com API已于2015年11月15日永久关闭


#32楼

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

$(document).ready( function() {
    $.getJSON( "http://smart-ip.net/geoip-json?callback=?",
        function(data){
            alert( data.host);
        }
    );
});
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值