vue获取内网ip

前端解决方法

首先

内网IP的获取相对比较复杂,主要是需要依赖 webRTC 这么一个非常用的API

WebRTC,名称源自网页即时通信(英语:Web Real-Time Communication)的缩写,是一个支持网页浏览器进行实时语音对话或视频对话的API。它于2011年6月1日开源并在Google、Mozilla、Opera支持下被纳入万维网联盟的W3C推荐标准。

webRTC 是HTML 5 的一个扩展,允许去获取当前客户端的IP地址,可以查看当前网址:net.ipcalf.com/

但如果使用 chrome 浏览器打开,此时可能会看到一串类似于:

e87e041d-15e1-4662-adad-7a6601fca9fb.local

的机器码,这是因为chrome 默认是隐藏掉 内网IP地址的,可以通过修改 chrome 浏览器的配置更改此行为:

1、在chrome 浏览器地址栏中输入:chrome://flags/

2、搜索 #enable-webrtc-hide-local-ips-with-mdns 该配置 并将属性改为disabled

3、点击relaunch 浏览器即可查看到本机的内网IP地址

其次

在代码中编写该方法

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);
      };
    },

最后

this.getUserIP((ip) => {
      this.remoteIp = ip
    });

这样就获取到ip了
注意:记得一定要确保用户的浏览器要经过第一步的设置,不然可能就无法拿到了,且该方法只测试了谷歌浏览器

后台解决方法

nginx配置修改

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

你可能感兴趣的:(vue获取内网ip)