// 获取当前设备的 IP 地址可以通过使用 Web API 或第三方服务。由于浏览器安全限制,直接获取本地 IP 地址较为复杂,通常需要借助服务器或第三方服务。
// 以下是通过第三方服务(如 ipify)来获取公共 IP 地址的示例代码:
async function getPublicIP() {
try {
const response = await fetch('https://api.ipify.org?format=json');
const data = await response.json();
console.log('Public IP:', data.ip);
return data.ip;
} catch (error) {
console.error('Error fetching public IP:', error);
return null;
}
}
getPublicIP();
// 如果你需要获取局域网内的本地 IP 地址,可以考虑使用 WebRTC,但这种方法并不总是可靠,并且可能因浏览器和网络配置而异。
// 示例代码:使用 WebRTC 获取本地 IP 地址
function getLocalIPs(callback) {
let ips = [];
const peerConnection = new RTCPeerConnection({
iceServers: []
});
peerConnection.createDataChannel('');
peerConnection.onicecandidate = (event) => {
if (event.candidate) {
const ipRegex = /([0-9]{1,3}\.){3}[0-9]{1,3}/;
const ip = event.candidate.candidate.match(ipRegex);
if (ip && ips.indexOf(ip[0]) === -1) {
ips.push(ip[0]);
}
} else {
peerConnection.close();
callback(ips);
}
};
peerConnection.createOffer().then((offer) => {
peerConnection.setLocalDescription(offer);
}).catch((error) => {
console.error('Error creating offer:', error);
callback([]);
});
}
getLocalIPs((ips) => {
console.log('Local IPs:', ips);
});
获取公共 IP:
fetch
请求调用 ipify
的 API 来获取当前设备的公共 IP 地址。获取本地 IP:
RTCPeerConnection
对象,并通过监听 onicecandidate
事件来捕获本地 IP 地址。上一篇:js 结构赋值
下一篇:js 立即执行函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站