其他分享
首页 > 其他分享> > js获取设备内网ip

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>

 

测试结果:

 

标签:function,rtc,ip,js,displayAddrs,addrs,var,line,内网
来源: https://www.cnblogs.com/c2g5201314/p/12243106.html