在前端js代码中获取用户的IP地址:【本文受版权保护】
【关注微信公众号:wwwtangshuangnet】著作权归作者所有,禁止商业用途转载。【作者:唐霜】【原创不易,请尊重版权】本文作者:唐霜,转载请注明出处。export function getUserIP() {
return new Promise((resolve, reject) => {
const RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
const pc = new RTCPeerConnection({
iceServers: []
})
const noop = function() {}
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]) {
resolve(ip)
}
localIPs[ip] = true
}
//create a bogus data channel
pc.createDataChannel('')
// create offer and set local description
try {
pc.createOffer(function(sdp) {
sdp.sdp.split('\n').forEach(function(line) {
if (line.indexOf('candidate') < 0) {
return
}
line.match(ipRegex).forEach(iterateIP)
})
pc.setLocalDescription(sdp, noop, noop)
}, function(sdp) {
reject()
})
}
catch (err) {
reject(err)
}
//listen for candidate events
pc.onicecandidate = function(ice) {
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) {
return
}
ice.candidate.candidate.match(ipRegex).forEach(iterateIP)
}
})
}
需要用到webRTC,如果不支持该接口,转载请注明出处:www.tangshuang.net未经授权,禁止复制转载。那就无法获取。
【版权所有】唐霜 www.tangshuang.net著作权归作者所有,禁止商业用途转载。本文作者:唐霜,转载请注明出处。
