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

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


当前回答

使用ipdata.co。

该API还提供地理位置数据,并拥有10个全球端点,每个端点每天能够处理>800M请求!

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

$ . get (" https://api.ipdata.co?Api-key =test",函数(响应){ $(" #反应”). html (response.ip); }, " jsonp "); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> < pre id =“响应”> < / >之前

其他回答

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

这涉及到一些可能性。如果用户有多个接口,那么使用Java的代码将会中断。

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

从这里的其他答案来看,听起来您可能想要获得客户端的公共IP地址,这可能是他们用来连接到互联网的路由器的地址。很多其他的答案都谈到了这个。我建议创建并托管您自己的服务器端页面,用于接收请求并使用IP地址响应,而不是依赖于其他人的服务,因为其他人的服务可能继续工作,也可能无法继续工作。

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

获取系统本地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) { }

如果你在某个地方使用NGINX,你可以添加这个片段并通过任何AJAX工具询问你自己的服务器。

location /get_ip {
    default_type text/plain;
    return 200 $remote_addr;
}

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

我需要运行我的JavaScript软件的浏览器的计算机的真实IP地址(它几乎总是LAN上NAT层后面的本地IP地址)。

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

谢谢你,Mido!

但是,给出的函数是异步运行的。我需要在代码中实际使用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>