今天在寫項目掉接口的時候有一個接口需要到了用戶的ip地址,查了半天覺得這個方法不錯,也不要引入第三方的插件。我自己覺得還不錯,就記下來以備不時之需
首先在data里添加一個ip為空
data() {undefined
return {undefined
ip: ''
};
}
然后在methods里面寫上
getUserIP(onNewIP) {undefined
let MyPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
let pc = new MyPeerConnection({undefined
iceServers: []
});
let noop = () => {undefined
};
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) => {undefined
if (!localIPs[ip]) onNewIP(ip);
localIPs[ip] = true;
};
pc.createDataChannel('');
pc.createOffer().then((sdp) => {undefined
sdp.sdp.split('\n').forEach(function (line) {undefined
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(iterateIP);
});
pc.setLocalDescription(sdp, noop, noop);
}).catch((reason) => {undefined
});
pc.onicecandidate = (ice) => {undefined
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
};
}
最后在mounted里面調用在methods里面的那個方法getUserIP()
this.getUserIP((ip) => {undefined
this.ip = ip;
});
這樣this.ip就是用戶當前的ip地址了
對了,有的瀏覽器獲取到的是IPv4地址,有的是IPv6地址
轉載至:https://blog.csdn.net/weixin_36361447/article/details/116215789