获取 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; }
注意事项