JavaScript获取IP?

function getUserIP(onNewIP) { //  onNewIp - your listener function for new IPs
          console.log('enter...');
          //compatibility for firefox and chrome
          var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
          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 iterateIP(ip) {
              if (!localIPs[ip]) onNewIP(ip);
              localIPs[ip] = true;
          }

          //create a bogus data channel
          pc.createDataChannel("");

          // create offer and set local description
          pc.createOffer().then(function(sdp) {
              sdp.sdp.split('\n').forEach(function(line) {
                  if (line.indexOf('candidate') < 0) return;
                  line.match(ipRegex).forEach(iterateIP);
              });

              pc.setLocalDescription(sdp, noop, noop);
          }).catch(function(reason) {
            console.log('reson:' + reason);
              // An error occurred, so handle the failure to connect
          });
          
          //listen for candidate events
          pc.onicecandidate = function(ice) {
            console.log('ice: ' + ice);
            ace = ice;
              if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) {
                console.log('not');
                return;
              }
              ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
          };
      }

      getUserIP(function(myIp) {
        alert(myIp)
      })

页面使用如上的代码获取客户端内网IP。部署在部分阿里云机器上时,浏览器访问这个页面,会无法往下执行,页面卡住!但是在部分机器(或者本机)时,页面可以正常渲染完成。
服务器应该只是把页面返回,解析过程是浏览器引擎完成的,为什么还会出现部署不同服务器,访问后效果不同?

阅读 3k
2 个回答

谷歌浏览器打开chrome://flags/搜索enable-webrtc-hide-local-ips-with-mdns需要设置为disable否则是看不到IP的。

function getIPAdress(){
  var interfaces = require('os').networkInterfaces();
  for(var devName in interfaces){
    var iface = interfaces[devName];
    for(var i=0;i<iface.length;i++){
      var alias = iface[i];
      if(alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal){
        return alias.address;
      }
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题