浏览器如何获取本机ip地址

浏览器如何获取本机的 IP 地址呢,方案有很多,简单的可以去 (https://ip.cn/)[https://ip.cn/] 获取本机 IP
但有时我们要在业务中拿到客户端 IP,该怎么办呢,也有相应的解决方案,例如一些三方接口:搜狐淘宝腾讯

接下来,我们使用 WebRTC API 来获取本机 IP
具体操作如下:

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
function IPQuery(backcall) {
// 兼容性处理
const MyPeerConnection =
window.RTCPeerConnection ||
window.mozRTCPeerConnection ||
window.webkitRTCPeerConnection;
// 创建实例
const pc = new MyPeerConnection({
// 连接 STUN协议服务器
iceServers: [{ url: 'stun:stun.l.google.com:19302' }],
});
let localIPs = { '0.0.0.0': 1 };
let noop = () => {};
let ipRegex =
/([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
function ipIterate(ip) {
if (!localIPs[ip]) backcall(ip);
localIPs[ip] = true;
}
// 创建数据信道
pc.createDataChannel('');
pc.createOffer().then(function (sdp) {
sdp.sdp.split('\n').forEach(function (line) {
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(ipIterate);
});
pc.setLocalDescription(sdp, noop, noop);
});
// 聆听候选事件
pc.onicecandidate = function (ice) {
console.log(ice);
if (
!ice ||
!ice.candidate ||
!ice.candidate.candidate ||
!ice.candidate.candidate.match(ipRegex)
)
return;
ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
};
}

IPQuery(ip => {
console.log(ip);
// xxx.xxx.xxx.xxx
});
-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!
0%