vue 獲取用戶ip,在vue項目中獲取用戶ip地址


今天在寫項目掉接口的時候有一個接口需要到了用戶的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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM