美文网首页
JS获取公网、内网IP

JS获取公网、内网IP

作者: 秋秋秋web | 来源:发表于2018-11-28 09:44 被阅读40次

HTML:

<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>  

JS:

getIpAddress(){

          this.getIPs(function(ip){

              console.log('内网地址',ip);

          });

          console.log('公网地址',returnCitySN["cip"])

      },

      getIPs(callback){  

          var ip_dups = {};

          //compatibility for firefox and chrome

          var RTCPeerConnection = window.RTCPeerConnection

              || window.mozRTCPeerConnection

              || window.webkitRTCPeerConnection;

          //bypass naive webrtc blocking

          if (!RTCPeerConnection) {

              var iframe = document.createElement('iframe');

              //invalidate content script

              iframe.sandbox = 'allow-same-origin';

              iframe.style.display = 'none';

              document.body.appendChild(iframe);

              var win = iframe.contentWindow;

              window.RTCPeerConnection = win.RTCPeerConnection;

              window.mozRTCPeerConnection = win.mozRTCPeerConnection;

              window.webkitRTCPeerConnection = win.webkitRTCPeerConnection;

              RTCPeerConnection = window.RTCPeerConnection

                  || window.mozRTCPeerConnection

                  || window.webkitRTCPeerConnection;

          }

          //minimal requirements for data connection

          var mediaConstraints = {

              optional: [{RtpDataChannels: true}]

          };

          //firefox already has a default stun server in about:config

          //    media.peerconnection.default_iceservers =

          //    [{"url": "stun:stun.services.mozilla.com"}]

          var servers = undefined;

          if(window.webkitRTCPeerConnection)

              servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};

          var pc = new RTCPeerConnection(servers, mediaConstraints);

          pc.onicecandidate = function(ice){

              if(ice.candidate){

                  var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/

                  var ip_addr = ip_regex.exec(ice.candidate.candidate)[1];

                  if(ip_dups[ip_addr] === undefined)

                      callback(ip_addr);

                  ip_dups[ip_addr] = true;

              }

          };

          pc.createDataChannel("");

          pc.createOffer(function(result){

              pc.setLocalDescription(result, function(){}, function(){});

          }, function(){});

      }

相关文章

网友评论

      本文标题:JS获取公网、内网IP

      本文链接:https://www.haomeiwen.com/subject/oskqbftx.html