如何使用 JavaScript 获取 local/internal IP

How to get local/internal IP with JavaScript

如何使用 WebRTC.

获取本地客户端 IP

我不需要客户端的REMOTE_ADDR,而是他的本地网络IP。 我以前在 sharedrop.com 这样的网站上看到过这个,它使用 WebRTC 识别同一网络中的计算机。

在 PHP 中,我这样做是为了获取客户端远程 IP:

<?php
  echo $_SERVER["REMOTE_ADDR"]; // which would return 72.72.72.175
?>

我查看了 Whosebug,但每个问题都是使用远程地址回答的。

如何使用 JavaScript 而不是远程地址获取我的本地 IP(例如 192.168.1.24)。

更新

不幸的是,以下答案不再有效,因为浏览器出于安全考虑更改了此行为。参见 this Whosebug Q&A for more details


我从哪里获取代码 --> Source

您可以在 --> Demo

找到演示

我修改了源代码,减少了行数,没有发出任何眩晕请求,因为您只需要本地 IP 而不是 Public IP,以下代码适用于最新的 Firefox 和 Chrome:

    window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;   //compatibility for firefox and chrome
    var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};      
    pc.createDataChannel("");    //create a bogus data channel
    pc.createOffer(pc.setLocalDescription.bind(pc), noop);    // create offer and set local description
    pc.onicecandidate = function(ice){  //listen for candidate events
        if(!ice || !ice.candidate || !ice.candidate.candidate)  return;
        var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];
        console.log('my IP: ', myIP);   
        pc.onicecandidate = noop;
    };
    

这里发生的事情是,我们正在创建一个虚拟对等点连接,为了让远程对等点联系我们,我们通常会相互交换 ice candidates。读取 ice candiates 我们可以知道用户的 ip。

您可以在现代浏览器上使用此版本(使用 Promisesasync / await

// minified onliner, 219b
const ip = await new Promise((s,f,c=new RTCPeerConnection(),k='candidate')=>(c.createDataChannel(''),c.createOffer(o=>c.setLocalDescription(o),f),c.onicecandidate=i=>i&&i[k]&&i[k][k]&&c.close(s(i[k][k].split(' ')[4]))))
// cleaned, 363b
const ip = await new Promise((resolve, reject) => {
  const conn = new RTCPeerConnection()
  conn.createDataChannel('')
  conn.createOffer(offer => conn.setLocalDescription(offer), reject)
  conn.onicecandidate = ice => {
    if (ice && ice.candidate && ice.candidate.candidate) {
      resolve(i.candidate.candidate.split(' ')[4])
      conn.close()
    }
  }
})