mounted() {
this.getUserIP((ip)=>{
console.log('ip=')
console.log(ip)
})
},
methods: {
getUserIP (onNewIP) {
//获取不到可能是因为chrome浏览器版本过高,需要修改浏览器配置如下
//在chrome地址栏输入:chrome://flags/#enable-webrtc-hide-local-ips-with-mdns
// 把 Anonymize local IPs exposed by WebRTC 设置为 disabled
//不能确保每一个浏览器都设置打开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构建时定义process.env属性,这样全局可获得
// 获取本机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
}
}
}
}文章来源:https://www.toymoban.com/news/detail-408315.html
module.exports = {
...,
config.plugin('define').tap(args => {
args[0]['process.env'].CURRENT_IP = JSON.stringify(getIpAdress())
return args
})
},
...
}
文章来源地址https://www.toymoban.com/news/detail-408315.html
到了这里,关于vue获取本机ip地址的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!