部分瀏覽器支援 WebRTC,可以透過 STUN 伺服器取得連線候選資訊。從中解析出的 IP,可能包含內網位址或對外位址。此類技術應用時,應遵守隱私規範並取得使用者同意。
function getIPs(callback) {
const ipDups = {};
const RTCPeerConnection =
window.RTCPeerConnection ||
window.mozRTCPeerConnection ||
window.webkitRTCPeerConnection;
if (!RTCPeerConnection) {
return;
}
const mediaConstraints = {
optional: [{ RtpDataChannels: true }]
};
const servers = undefined;
const pc = new RTCPeerConnection(servers, mediaConstraints);
pc.onicecandidate = function (ice) {
if (!ice.candidate) {
return;
}
const ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/;
const match = ipRegex.exec(ice.candidate.candidate);
if (match) {
const ip = match[1];
if (ipDups[ip] === undefined) {
callback(ip);
ipDups[ip] = true;
}
}
};
pc.createDataChannel('');
pc.createOffer(function (result) {
pc.setLocalDescription(result, function () {});
}, function () {});
}
getIPs(function (ip) {
console.log(ip);
});不同瀏覽器對 WebRTC 的支援程度不同,部分環境可能需要 HTTPS 或特定權限。此外,取得 IP 屬於敏感資訊,正式環境應明確告知使用者用途,並遵循相關隱私政策。