上一篇
html本地ip代码
- 行业动态
- 2025-05-01
- 8
“
html,,,,,const pc = new RTCPeerConnection();,pc.createDataChannel('');,pc.onicecandidate = e => {, if (e.candidate) return;, alert(
本地IP: ${pc.localDescription.sdp.split(‘n’)[1].split(‘ ‘)[1]}`);,};,pc.createOffer().then(d=>pc.setLocalDescription(d));,,
获取本地IP地址的HTML实现方法
核心原理
浏览器出于安全限制无法直接获取本地IP,需通过以下两种方式间接实现:
- WebRTC技术:利用
RTCPeerConnection
获取局域网IP - 外部API服务:调用第三方接口获取公网IP
WebRTC实现方案
<!DOCTYPE html> <html> <body> <h3>您的本地IP地址:</h3> <div id="ip"></div> <script> const pc = new RTCPeerConnection(); pc.createDataChannel(""); pc.createOffer().then(offer => pc.setLocalDescription(offer)); pc.onicecandidate = event => { if (event.candidate) { const ip = event.candidate.candidate.split(' ')[4]; document.getElementById('ip').textContent = ip; } }; </script> </body> </html>
外部API实现方案
<!DOCTYPE html> <html> <body> <h3>您的公网IP地址:</h3> <div id="public-ip"></div> <script> fetch('https://api.ipify.org?format=json') .then(response => response.json()) .then(data => { document.getElementById('public-ip').textContent = data.ip; }); </script> </body> </html>
方案对比表
特性 | WebRTC方案 | API方案 |
---|---|---|
获取IP类型 | 内网IP | 公网IP |
浏览器兼容性 | IE/Safari不完整支持 | 全平台支持 |
隐私安全性 | 无数据传输 | 需信任第三方服务 |
实现复杂度 | 中等 | 简单 |
典型应用场景 | 局域网设备识别 | 公网IP展示 |
常见问题与解答
Q1:为什么Safari浏览器无法正常显示IP?
A1:Safari浏览器禁用了WebRTC的ICE候选功能,导致无法通过此方法获取IP,建议改用其他浏览器(如Chrome/Firefox)或采用API方案。
Q2:如何同时显示内外网IP?
A2:可组合两种方案,示例如下:
<div>内网IP:<span id="local-ip"></span></div> <div>外网IP:<span id="public-ip"></span></div> <script> // WebRTC获取内网IP const pc = new RTCPeerConnection(); pc.onicecandidate = event => { if(event.candidate) { document.getElementById('local-ip').textContent = event.candidate.candidate.split(' ')[4]; } }; pc.createDataChannel(""); pc.createOffer().then(offer => pc.setLocalDescription(offer)); // API获取外网IP fetch('https://api.ipify.org?format=json') .then(response => response.json()) .then(data => { document.getElementById('public-ip').textContent = data.ip; }); </script>