浏览器获取客户端ip(非远程请求或依赖第三方api)
浏览器获取本机ip或者mac由于权限问题无法直接获取,客户端无node环境,仅仅访问网站地址是无法直接获取到本机的网络信息的,综合目前唯一的方式就是客户端安装浏览器插件WebRTCControl,可以支持edge/谷歌/360等浏览器
import tool from '@/utils/tool'
const getIP = (callback) => {
let recode = {}
let RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection
if (!RTCPeerConnection) {
let win = iframe.contentWindow
RTCPeerConnection = win.RTCPeerConnection || win.mozRTCPeerConnection || win.webkitRTCPeerConnection
}
//创建实例,生成连接
let pc = new RTCPeerConnection()
// 匹配字符串中符合ip地址的字段
function handleCandidate(candidate) {
let ip_regexp = /([0-9]{1,3}(\.[0-9]{1,3}){3}|([a-f0-9]{1,4}((:[a-f0-9]{1,4}){7}|:+[a-f0-9]{1,4}){6}))/
if (candidate.match(ip_regexp)) {
let ip_isMatch = candidate.match(ip_regexp)[1]
if (!recode[ip_isMatch]) {
callback(ip_isMatch)
recode[ip_isMatch] = true
}
}
}
//监听icecandidate事件
pc.onicecandidate = (ice) => {
if (ice.candidate) {
handleCandidate(ice.candidate.candidate)
}
}
//建立一个伪数据的通道
pc.createDataChannel('')
pc.createOffer(
(res) => {
pc.setLocalDescription(res)
},
() => {}
)
//延迟,让一切都能完成
setTimeout(() => {
let lines = pc.localDescription.sdp.split('\n')
lines.forEach((item) => {
if (item.indexOf('a=candidate:') === 0) {
handleCandidate(item)
}
})
}, 1000)
}
getIP((res) => {
tool.data.set('LOC_IP', res)
})Last updated