-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathip.html
More file actions
39 lines (36 loc) · 1.38 KB
/
ip.html
File metadata and controls
39 lines (36 loc) · 1.38 KB
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
<!DOCTYPE html>
<html>
<body>
<p>您的局域网IP是:<span id="local-ip"></span></p>
<script>
function getLocalIP() {
const RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
// 创建一个虚拟的RTCPeerConnection,不连接任何STUN服务器
const pc = new RTCPeerConnection({ iceServers: [] });
// 创建一个数据通道
pc.createDataChannel('');
// 创建offer(提议)
pc.createOffer().then(offer => pc.setLocalDescription(offer));
// 监听ICE候选信息
pc.onicecandidate = function(event) {
if (event.candidate) {
const candidate = event.candidate.candidate;
// 使用正则表达式从候选信息中匹配IPv4地址
const ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/;
const match = ipRegex.exec(candidate);
if (match) {
const ip = match[1];
// 检查是否是局域网IP(以192.168、172.16-31、10.开头)
if (ip.startsWith('192.168.') || ip.startsWith('172.1') || ip.startsWith('10.')) {
document.getElementById('local-ip').textContent = ip;
pc.onicecandidate = null; // 获取到后取消监听
pc.close(); // 关闭连接
}
}
}
};
}
getLocalIP();
</script>
</body>
</html>