公司项目有一个功能需求要获取本地主机IP地址,在网上找了一些方法试了一下

129 阅读1分钟
//测试一
const os = import.meta.globEager('os');

mounted() {
    console.log(os);
},
//结果os为{}空对象


//测试二
//utils下创建getIp.ts
export function getUserIP(onNewIP) {
  let MyPeerConnection = window.RTCPeerConnection;
  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);
  };
}
//使用文件
import { getUserIP } from '@/utils/getIp';

created() {
    getUserIP((ip) => {
      this.ip = ip;
      console.log(this.ip);
    });
  },
//结果新版本谷歌浏览器(101)不能使用,旧版本(90)可以使用

结论:webrtc已不支持获取用户本地IP地址,用于保护用户隐私,但是老版本浏览器仍然可以使用。

参考文章:www.notion.so/vue3-IP-743…