獲取 ip 地址的方法:直接獲取webrtc api。使用 navigator.mediadevices.getusermedia()。通過服務器代理發送 ajax 或 fetch 請求。
如何用 JavaScript 獲取 IP 地址
直接獲取
WebRTC API
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;
}
登錄后復制
navigator.mediaDevices.getUserMedia()
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;
}
登錄后復制
通過服務器代理
使用 AJAX 或 fetch
向服務器發送請求,服務器響應中包含 IP 地址。
async function getIP() {
const response = await fetch('/get-ip');
const data = await response.json();
return data.ip;
}
登錄后復制
注意事項
WebRTC API 和 navigator.mediaDevices.getUserMedia() 只能在安全連接(HTTPS)上使用。
服務器代理方法需要后端支持。
獲取到的 IP 地址可能是本地 IP 地址,而不是外部 IP 地址。






