获取 IP 地址的方法:直接获取WebRTC API。使用 navigator.mediaDevices.getUserMedia()。通过服务器代理发送 AJAX 或 fetch 请求。
如何用 JavaScript 获取 IP 地址
直接获取
async function getIP() { const configuration = { iceServers: [ { urls: ['stun:stun.l.google.com:19302'] } ] }; const peerConnection = new RTCPeerConnection(configuration); const iceCandidate = await new Promise((resolve) => { peerConnection.onicecandidate = (e) => { if (e.candidate && e.candidate.type === 'srflx') { resolve(e.candidate.address); } }; }); peerConnection.close(); return iceCandidate; }
async function getIP() { const mediaStream = await navigator.mediaDevices.getUserMedia({ video: false, audio: false }); const peerConnection = new RTCPeerConnection(); const sender = peerConnection.addTrack(mediaStream.getTracks()[0], mediaStream); const iceCandidate = await new Promise((resolve) => { peerConnection.onicecandidate = (e) => { if (e.candidate && e.candidate.type === 'srflx') { resolve(e.candidate.address); } }; }); sender.stop(); peerConnection.close(); return iceCandidate; }
通过服务器代理
向服务器发送请求,服务器响应中包含 IP 地址。
async function getIP() { const response = await fetch('/get-ip'); const data = await response.json(); return data.ip; }
注意事项
以上就是如何用js获取ip地址的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号