学习笔记——【JS浏览器获取本地IP的方法】

学习使我快乐,沉迷学习,日渐消瘦!

JS获取本地IP的方法

通常情况下,出于安全性考虑,浏览器是不允许随意获取用户本地IP的。但是架不住你的上司跟你说,来咱们做个统计功能,包括统计用户IP。

为了五斗米,我还是折了腰,于是苦逼的我……

获取本地IP的方法

目前通过浏览器获取IP的方法主要有以下三种:

1、IE浏览器的ActiveX插件运行的情况下,可以利用ActiveObject获取。
2、利用第三方平台的接口返回,比如新浪、天平洋的接口。
3、利用WebRTC技术获取。

当然了,这三种方法都有着非常明显的弊端:
方案一:只支持IE,领导会打死你。
方案二:首先需要支持外网,其次第三方接口不在可控范围内,人家改了接口怎么办?
方案三:虽然大多主流浏览器已经支持了WebRTC,但是webRTC只能在https这种安全协议下才能使用。且不兼容IE浏览器。

综上,如果你们的平台使用的是https安全协议,那么用方案一 + 方案三,很完美。如果是http且支持外网的情况下,建议第二种。

利用ActiveObject获取用户IP

首先,这个只有IE浏览器,且设置支持ActiveX时才可以用哦!

ActiveObject语法:

let newObject = new ActiveXObject("servername.typename"[, "location"]);

话不多说,上代码(亲测有效):


<html>
  <head>
      <title>get Ip and MAC!title>
      <meta http-equiv=Content-Type content="text/html; charset=gb2312">
  head>
  <body>
      <script type="text/javascript">
          let locator = new ActiveXObject('WbemScripting.SWbemLocator');
          var service = locator.ConnectServer("."); //连接本机服务器
          var properties = service.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=TRUE");
          var e = new Enumerator (properties);
          let ipInfo, macInfo;
          for (;!e.atEnd();e.moveNext ())
          {
              var p = e.item ();
              ipInfo ="IP:" + p.IPAddress(0) + " "; //IP地址为数组类型,子网俺码及默认网关亦同
              macInfo ="MAC:" + p.MACAddress + " "; //网卡物理地址
          }
          console.log(ipInfo);
          console.log(macInfo);
      script>
  body>
html>

利用第三方接口获取用户IP

现在用的比较多的第三方免费开放接口一般是搜狐提供的接口:http://pv.sohu.com/cityjson?ie=utf-8。

所以通过script标签引入这个接口就可以了,这样还可以避免跨域的问题。
话不多说,上代码(亲测有效):


<html>
  <head>
      <title>get Ip and MAC!title>
      <meta http-equiv=Content-Type content="text/html; charset=gb2312">
  head>
  <body>
    <script src="http://pv.sohu.com/cityjson?ie=utf-8">script>
    <script type="text/javascript">
      document.write(returnCitySN["cip"]+','+returnCitySN["cname"])
    script>
  body>
html>

利用webRTC获取用户IP

注:webRTC的作用是实现基于网页的视频会议,所以出于安全性考虑,webRTC只支持https或者本地文件的方式访问。

如果大家调试不方便,可以在本地修改一下浏览器的目标地址。
操作:右键浏览器图标,属性 -》 快捷方式 -》目标
修改成:

“C:\Users\Administrator\AppData\Local\Google\Chrome\Application\chrome.exe”
–unsafely-treat-insecure-origin-as-secure=“http://ip:port” --user-data-dir=本地目录

然后重启浏览器就可以使用http调试webRTC了。

简单介绍下webRTC,web real-time communication 的简写,意思就是网页实时通信,是一个支持网页浏览器进行实时语音对话或视频对话的API。浏览器底层封装支持的,无需引入插件,就可以实现视频对话等功能。

所以我们可以利用webRTC来获取本地IP。

话不多说,上代码(亲测有效):


<html>
   <head>
     <title>get Ip and MAC!title>
     <meta http-equiv=Content-Type content="text/html; charset=gb2312">
   head>
   <body>
     <script>
      function findIP(onNewIP) {
        let myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; // RTCPeerConnection是WebRTC用于构建点对点之间稳定、高效的流传输的组件。兼容火狐、谷歌等
        let pc = new myPeerConnection({ // 创建点对点连接的RTCPeerConnection的实例
          iceServers: [{"url": "stun:stun.l.google.com:19302"}]
        }); // webRTC使用了ICE协议框架,包括STUN 和 TURN两个协议。我这里连接的是STUN协议服务器。STUN Server的作用是接受客户端的请求,并且把客户端的公网IP、Port封装到ICECandidate中。
        let noop = function() {};
        let localIPs = {}; // 记录有没有被调用到onNewIP这个listener上
        let ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
        let key;
        
        function ipIterate(ip) {
          if (!localIPs[ip]) onNewIP(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) { //listen for candidate events
          if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
          ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
        };
      }
      let ul = document.createElement('ul');
      ul.textContent = 'Your IPs are: '
      document.body.appendChild(ul);
      
      function addIP(ip) {
        console.log('got ip: ', ip);
        var li = document.createElement('li');
        li.textContent = ip;
        ul.appendChild(li);
      }
      findIP(addIP);
    script>
    body>
html>

你可能感兴趣的:(前端,学习)