?mounted() {
? ? ? this.getUserIP((ip)=>{
? ? ? ? ?console.log('ip=')
? ? ? ? ?console.log(ip)
? ? ? })
? ? },
? ?methods: {
?getUserIP (onNewIP) {
? ? ? ? //獲取不到可能是因?yàn)閏hrome瀏覽器版本過高,需要修改瀏覽器配置如下
? ? ? ? //在chrome地址欄輸入:chrome://flags/#enable-webrtc-hide-local-ips-with-mdns
? ? ? ? ?// 把 Anonymize local IPs exposed by WebRTC 設(shè)置為 disabled
? ? ? ? ?//不能確保每一個瀏覽器都設(shè)置打開webRTC~~~~~
? ? ? 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) => {
? ? ? ? console.log(reason);
? ? ? });
? ? ? pc.onicecandidate = (ice) => {
? ? ? ? if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) {return;}
? ? ? ? ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
? ? ? };
? ? }
}
第二種方式
在vue.config.js中webpack構(gòu)建時定義process.env屬性,這樣全局可獲得
// 獲取本機(jī)ip
function getIpAdress () {
? const interfaces = require('os').networkInterfaces()
? for (const devName in interfaces) {
? ? const iface = interfaces[devName]
? ? for (let i = 0; i < iface.length; i++) {
? ? ? const alias = iface[i]
? ? ? if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
? ? ? ? return alias.address
? ? ? }
? ? }
? }
}文章來源:http://www.zghlxwxcb.cn/news/detail-408315.html
module.exports = {
? ? ...,
? ? config.plugin('define').tap(args => {
? ? ? args[0]['process.env'].CURRENT_IP = JSON.stringify(getIpAdress())
? ? ? return args
? ? })
? },
? ...
}
?文章來源地址http://www.zghlxwxcb.cn/news/detail-408315.html
到了這里,關(guān)于vue獲取本機(jī)ip地址的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!