本文介绍两种使用JavaScript获取本机IP地址的方法,主要依赖WebRTC技术。若浏览器限制导致无法获取,需调整Firefox、Chrome或Edge浏览器的特定配置项以解除隐藏IP的限制,从而正常显示本地IP地址。
方法一:获取本机IP地址
if(typeof window != 'undefined'){
var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
if (RTCPeerConnection) (()=>{
var rtc = new RTCPeerConnection()
rtc.createDataChannel(''); //创建一个可以发送任意数据的数据通道
rtc.createOffer( offerDesc => { //创建并存储一个sdp数据
rtc.setLocalDescription(offerDesc)
}, e => { console.log(e)})
rtc.onicecandidate =(evt) => { //监听candidate事件
if (evt.candidate) {
console.log('evt:',evt.candidate)
let ip_rule = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
var ip_addr = ip_rule.exec(evt.candidate.candidate)[1]
console.log('ip_addr:',ip_addr) //打印获取的IP地址
}}
})()
else{console.log("没有找到")}
}方法二:获取本机IP地址
//获取用户本地ip的方法
const getUserIP= (onNewIP)=> {
let MyPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
let pc = new MyPeerConnection({
iceServers: []
});
let noop = () => {
};
let localIPs = {};
let ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
let iterateIP = (ip) => {
if (!localIPs[ip]) onNewIP(ip);
localIPs[ip] = true;
};
pc.createDataChannel('');
pc.createOffer().then((sdp) => {
sdp.sdp.split('\n').forEach(function (line) {
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(iterateIP);
});
pc.setLocalDescription(sdp, noop, noop);
}).catch((reason) => {
});
pc.onicecandidate = (ice) => {
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
};
}
getUserIP((ip) => {
state.ip=ip
console.log(ip)
console.log(state.ip)
});如果未能成功获取到IP地址,通常是因为浏览器出于隐私保护进行了限制。此时需要按照以下步骤解除限制:
解决方案:
- 火狐(FireFox) 删除隐藏IP
在浏览器地址栏输入 about:config
搜索配置项 media.peerconnection.enabled 并将其值改为 false(刷新程序后,IP即可正常显示)
- 谷歌(Chrome) 删除隐藏IP
在浏览器地址栏输入:chrome://flags/#enable-webrtc-hide-local-ips-with-mdns
将 Anonymize local IPs exposed by WebRTC 设置为 disabled(刷新程序后,IP即可正常显示)
- Edge浏览器删除隐藏IP
在浏览器地址栏输入: edge://flags/#enable-webrtc-hide-local-ips-with-mdns
将 Anonymize local IPs exposed by WebRTC 设置为 disabled(刷新程序后,IP即可正常显示)
总结
到此这篇关于JS获取本机IP地址的2种方法的文章就介绍到这了,更多相关JS获取本机IP地址内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!