原生JS获取公网IP地址

| |
[不指定 2024/10/11 16:39 | by 刘新修 ]
JavaScript代码
  1. function getUserIP(callback) {  
  2.     var ip_dups = {};  
  3.     var RTCPeerConnection = window.RTCPeerConnection  
  4.         || window.mozRTCPeerConnection  
  5.         || window.webkitRTCPeerConnection;  
  6.     var useWebKit = !!window.webkitRTCPeerConnection;  
  7.     var mediaConstraints = {  
  8.         optional: [{RtpDataChannels: true}]  
  9.     };  
  10.     var servers = {  
  11.         iceServers: [  
  12.             {urls: "stun:stun.services.mozilla.com"},  
  13.             {urls: "stun:stun.l.google.com:19302"},  
  14.         ]  
  15.     };  
  16.     var pc = new RTCPeerConnection(servers, mediaConstraints);  
  17.     function handleCandidate(candidate){  
  18.         var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/  
  19.         var hasIp = ip_regex.exec(candidate)  
  20.         if (hasIp) {  
  21.             var ip_addr = ip_regex.exec(candidate)[1];  
  22.             if(ip_dups[ip_addr] === undefined)  
  23.                 callback(ip_addr);  
  24.             ip_dups[ip_addr] = true;  
  25.         }  
  26.     }  
  27.     pc.onicecandidate = function(ice){  
  28.         if(ice.candidate) {  
  29.             handleCandidate(ice.candidate.candidate);  
  30.         }    
  31.     };  
  32.     pc.createDataChannel("");  
  33.     pc.createOffer(function(result){  
  34.       pc.setLocalDescription(result, function(){}, function(){});  
  35.     }, function(){});  
  36.     setTimeout(function(){  
  37.         var lines = pc.localDescription.sdp.split('\n');  
  38.         lines.forEach(function(line){  
  39.             if(line.indexOf('a=candidate:') === 0)  
  40.                 handleCandidate(line);  
  41.         });  
  42.     }, 1000);  
  43. }  
  44.   
  45.   
  46. getUserIP((ip) => {  
  47.   console.log("ipppp === ",ip)  
  48.   //ipppp ===  121.90.11.160  
  49. })  
H5/JS/CSS | 评论(0) | 引用(0) | 阅读(142)