3
最近项目中需要获取公司内网的用户IP,起初网上查到的都是通过访问外网接口(例如新浪接口http://counter.sina.com.cn/ip)获取客户端处在网络中的IP,但在公司内网环境中无法实现。后来查到可通过WebRTC方式实现,现将代码整理如下,WebRTC还有待研究。
function findIP(callback) { 
  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]) callback(ip);
    localIPs[ip] = true;
  }
  pc.createDataChannel(""); 
  pc.createOffer().then(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);
  }); 
  pc.onicecandidate = function(ice) { 
    if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
    ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
  };
}
 
findIP(function(ip){
  console.log('got ip: ', ip);
});

参考:
http://blog.csdn.net/u0133321...
https://developer.mozilla.org...
http://blog.nsfocus.net/%E4%B...
https://www.cnblogs.com/muluo...


Jerry
226 声望32 粉丝