// 获取本机IP的代码示例
// 使用 WebRTC 方式获取本机 IP 地址
function getLocalIP() {
return new Promise((resolve, reject) => {
const RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
if (!RTCPeerConnection) {
reject('RTCPeerConnection is not supported');
return;
}
const pc = new RTCPeerConnection({ iceServers: [] });
pc.createDataChannel('');
pc.onicecandidate = (e) => {
try {
if (e.candidate) {
const ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/;
const ip_address = ip_regex.exec(e.candidate.candidate)[1];
resolve(ip_address);
pc.close();
}
} catch (err) {
reject(err);
}
};
pc.createOffer().then((sdp) => {
pc.setLocalDescription(sdp);
}).catch(reject);
});
}
// 调用函数并处理结果
getLocalIP().then(ip => {
console.log('本机IP地址:', ip);
}).catch(error => {
console.error('获取IP地址失败:', error);
});
Promise 中。请注意,这种方法依赖于浏览器支持 WebRTC,并且可能在某些情况下无法获取到真实的公网 IP 地址,而只是局域网内的 IP 地址。
上一篇:js 数组函数
下一篇:js 二维码生成
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站