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

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


当前回答

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

其他回答

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

但是,您可以对https://hutils.loxal.net/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
}

这里的大多数答案都“绕过”服务器端代码的需要……攻击别人的服务器。这是一种完全有效的技术,除非您确实需要在不访问服务器的情况下获得IP地址。

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

请阅读mido的回答,了解如何使用WebRTC检索有用的客户端IP地址。

好吧,我偏离了这个问题,但我今天有一个类似的需求,尽管我无法使用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从服务器呈现。而在Javascript中,我只是加载这个值。

这可能对像你这样有类似需求的人(比如我,但我还没有弄清楚)有帮助。

干杯!

2021年更新:

正如最近一个新的Github存储库WebRTC - IP所示,你现在可以使用WebRTC泄露用户的公共IP地址。遗憾的是,由于逐渐转向mDNS(至少对于WebRTC),这种泄漏不适用于私有ip,在这里完全解释了。然而,这里有一个工作演示:

getIPs()。然后(res =>文档) <剧本剧本src = " https://cdn.jsdelivr.net/gh/joeymalvinni/webrtc-ip/dist/bundle.dev.js " > < / >

这个存储库的编译源代码可以在这里找到。




(前情提要)最终更新

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


更新:我一直想做一个最小/丑陋版本的代码,所以这里是一个ES6承诺代码:

var findIP =新的承诺(r = > {var w =窗口,= new (w.RTCPeerConnection | | w.mozRTCPeerConnection | | w.webkitRTCPeerConnection) ({iceServers: []}), b = () = > {}; a.createDataChannel (" "); a.createOffer (c = > a.setLocalDescription (c, b, b), b), a.onicecandidate = c = >{尝试{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)}捕捉(e) {}}}) / * * /用法示例 findIP。然后(ip =>文档。写入('your ip: ', ip))。Catch (e => console.error(e))

注意:如果你想要用户的所有IP(这可能更多地取决于他的网络),这个新的最小化代码将只返回一个IP,使用原始代码…


多亏了WebRTC,在WebRTC支持的浏览器中很容易获得本地IP(至少现在)。我修改了源代码,减少了行,不做任何stun请求,因为你只需要本地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 candidate(从本地会话描述和onicecanddateevent),我们可以知道用户的IP。

我从哪里获取代码——>源代码

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

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

作为奖励,地理定位信息将在同一调用中返回。