全国统一服务热线:400-633-9193

获取本机IP地址的实例(JavaScript / Node.js)

    网络     2017-12-25    2341

下面小编就为大家分享一篇使用JavaScript和Node.js获取本机IP地址的实例,具有很好的参考价值,希望对大家有所帮助

--web 客户端JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!-- 调用方式 -->
 
<body onload="checkCookie()"></body>
function getYourIP()
 
{
const RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (RTCPeerConnection) (function()
{
const rtc = new RTCPeerConnection({iceServers: []});
if (1 || window.mozRTCPeerConnection)
{
rtc.createDataChannel('', {reliable: false});
}
rtc.onicecandidate = function(evt)
{
if (evt.candidate) grepSDP(`a=${evt.candidate.candidate}`);
};
rtc.createOffer(function(offerDesc)
{
grepSDP(offerDesc.sdp);
rtc.setLocalDescription(offerDesc);
}, function(e) {console.warn('offer failed', e);});
const addrs = Object.create(null);
addrs['0.0.0.0'] = false;
function updateDisplay(newAddr)
{
if (newAddr in addrs) return;
addrs[newAddr] = true;
const displayAddrs = Object.keys(addrs).filter(function(k) {return addrs[k];});
for (let i = 0; i < displayAddrs.length; i++)
{
if (displayAddrs[i].length > 16)
{
displayAddrs.splice(i, 1);
i--;
}
}
console.info('您的IP: ', displayAddrs[0]);
}
function grepSDP(sdp)
{
sdp.split('\r\n').forEach(function(line, index, arr)
{
if (~line.indexOf('a=candidate'))
{
const parts = line.split(' '),
addr = parts[4],
type = parts[7];
if (type === 'host') updateDisplay(addr);
}
else if (~line.indexOf('c='))
{
const parts = line.split(' '),
addr = parts[2];
updateDisplay(addr);
}
});
}
})();
else
{
console.warn('请使用主流浏览器:chrome,firefox,opera,safari');
}
}

--web服务端Node.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const os = require('os');
  
 
module.exports =
{
getLocalIP : function()
{
const eth0 = os.networkInterfaces().eth0;
let localhost = null;
for (let i = 0; i < eth0.length; i++)
{
if (eth0[i].family == 'IPv4')
{
localhost = eth0[i].address;
}
}
return localhost;
},
};

以上这篇获取本机IP地址的实例(JavaScript / Node.js)就是小编分享给大家的全部内容了,希望能给大家一个参考


  分享到:  
0.1963s