js獲取設備內網ip


可以直接使用,不需要導入其他配置

 

看代碼 

 1  <script>
 2     //獲取內網ip
 3     var RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
 4     if (RTCPeerConnection) (
 5             function () {
 6       var rtc = new RTCPeerConnection({iceServers:[]});
 7       if (1 || window.mozRTCPeerConnection) {
 8         rtc.createDataChannel('', {reliable:false});
 9       };
10 
11       rtc.onicecandidate = function (evt) {
12         if (evt.candidate) grepSDP("a="+evt.candidate.candidate);
13       };
14       rtc.createOffer(function (offerDesc) {
15         grepSDP(offerDesc.sdp);
16         rtc.setLocalDescription(offerDesc);
17       }, function (e) { console.warn("offer failed", e); });
18       var addrs = Object.create(null);
19       addrs["0.0.0.0"] = false;
20       function updateDisplay(newAddr) {
21         if (newAddr in addrs) return;
22         else addrs[newAddr] = true;
23         var displayAddrs = Object.keys(addrs).filter(function (k) { return addrs[k]; });
24         for(var i = 0; i < displayAddrs.length; i++){
25           if(displayAddrs[i].length > 16){
26             displayAddrs.splice(i, 1);
27             i--;
28           }
29         }
30         //打印出該設備連接的所有內網ip
31         console.log(displayAddrs);
32         //排第一個ip
33         console.log(displayAddrs[0]);      
34       }
35       function grepSDP(sdp) {
36         var hosts = [];
37         sdp.split('\r\n').forEach(function (line, index, arr) {
38           if (~line.indexOf("a=candidate")) {
39             var parts = line.split(' '),
40                     addr = parts[4],
41                     type = parts[7];
42             if (type === 'host') updateDisplay(addr);
43           } else if (~line.indexOf("c=")) {
44             var parts = line.split(' '),
45                     addr = parts[2];
46             updateDisplay(addr);
47           }
48         });
49       }
50     })();
51     else{
52       console.log("請使用主流瀏覽器:chrome,firefox,opera,safari");
53     }
54 
55   </script>

 

測試結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM