JavaScript检测局域网IP地址

JavaScript detection of LAN IP address

我一直在使用下面的代码来检测客户端的局域网IP地址运行一些专有软件(请不要"you shouldn't do this",我没有写代码)。

function ip_local()
{
 var ip = false;
 window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection || false;

 if (window.RTCPeerConnection)
 {
  ip = [];
  var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};
  pc.createDataChannel('');
  pc.createOffer(pc.setLocalDescription.bind(pc), noop);

  pc.onicecandidate = function(event)
  {
   if (event && event.candidate && event.candidate.candidate)
   {
    var s = event.candidate.candidate.split('\n');
    ip.push(s[0].split(' ')[4]);
   }
  }
 }

 return ip;
}
ip_local();

来自另一个 Whosebug post,直到今天下午,代码已经运行了一年半。

因为我的本地 IP 似乎被检测为 153b3a68-e3fb-4451-9717-d9b3bc2b5c60.local 而不是通常的 192.168.0.11。

编辑: 如果有人关心,这个问题是不可绕过的,必须通过服务器端语言来解决,在我的情况下,我最终使用 PHP 作为临时 "bandaid" 来解决这个问题。

这是我的应用程序的一个问题,因为它会检测本地服务器是否在主机上 运行。如果它无法检测到 LAN IP 地址,它就无法执行此操作。

这是新安全标准的一部分,用于防止私有 IP 地址泄露。

另请参阅:https://datatracker.ietf.org/doc/html/draft-ietf-rtcweb-mdns-ice-candidates-02

总结:

As detailed in [IPHandling], exposing client private IP addresses by default maximizes the probability of successfully creating direct peer-to-peer connection between two clients, but creates a significant surface for user fingerprinting. [IPHandling] recognizes this issue, but also admits that there is no current solution to this problem; implementations that choose to use Mode 3 to address the privacy concerns often suffer from failing or suboptimal connections in WebRTC applications. This is particularly an issue on unmanaged networks, typically homes or small offices, where NAT loopback may not be supported.

This document proposes an overall solution to this problem by registering ephemeral mDNS names for each local private IP address, and then providing those names, rather than the IP addresses, to the web application when it gathers ICE candidates. WebRTC implementations resolve these names to IP addresses and perform ICE processing as usual, but the actual IP addresses are not exposed to the web application.