demand
The page needs to add a watermark, plus the current login terminal (browser) connected to the NETWORK IP, so the problem is how to get the current network IP?
The solution
The easiest thing to think about is fromnodejs os.networkInterfaces()
Don’t you just fetch it directly from the module?
I tried and found that I got an empty object
mounted () {
console.log(require('os').networkInterfaces())
},
Copy the code
For empty reasons expect to see the big guy comments add that they will also continue to explore ~
The first way to get it
The following code
Definition method:
methods: {
// Obtain the current network IP address
getUserIP (onNewIP) {
const MyPeerConnection =
window.RTCPeerConnection ||
window.mozRTCPeerConnection ||
window.webkitRTCPeerConnection
const pc = new MyPeerConnection({
iceServers: []})const noop = () = > {}
const localIPs = {}
const ipRegex = / ([0-9] {1, 3} \. ([0-9] {1, 3}, {3} | [a - f0-9] {1, 4} (: [a - f0-9] {1, 4}, {7})/g
const 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)
}
}
}
Copy the code
Where to get:
mounted () {
this.getUserIP((rs) = > {
console.log(rs)
})
},
Copy the code
note
The failure may be because the Chrome version is too early. You need to modify the browser configuration as follows
-
- Enter chrome://flags/#enable-webrtc-hide-local-ips-with-mdns in the chrome address bar
-
- Set the Anonymize Local IPs Exposed by WebRTC to disabled.
Second method of acquisition (recommended)
The process.env attribute is defined at webpack build time in vue.config.js so that it is globally available
// Obtain the local IP address
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
}
}
}
}
module.exports = { ... , config.plugin('define').tap(args= > {
args[0] ['process.env'].CURRENT_IP = JSON.stringify(getIpAdress())
return args
})
},
...
}
Copy the code
Afterword.
It has been proved that the second way to obtain the IP of the packaged computer is not available; The first approach was also abandoned because it could not ensure that every browser was set up to have webRTC open. Finally get the IP from the back end, ~~~~~
Take notes, help yourself!