vue中获取客户端IP地址
vue中获取客户端IP地址
获取ip方法

export function getUserIP(onNewIP) { 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) => { }); pc.onicecandidate = (ice) => { if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return; ice.candidate.candidate.match(ipRegex).forEach(iterateIP); }; }
调用getUserIP获取ip
<template> <h1>{{ ip }}</h1> </template> <script> import getUserIP from './utils' export default { data() { return { ip: '' }; }, methods: { }, mounted() { getUserIP((ip) => { this.ip = ip; }); } } </script> <style lang="scss" scoped> </style>
本文来自博客园,作者:l-coil,转载请注明原文链接:https://www.cnblogs.com/l-coil/p/12790668.html
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步