vue獲取內(nèi)網(wǎng)ip

前端解決方法

首先

內(nèi)網(wǎng)IP的獲取相對比較復(fù)雜,主要是需要依賴 webRTC 這么一個(gè)非常用的API

WebRTC,名稱源自網(wǎng)頁即時(shí)通信(英語:Web Real-Time Communication)的縮寫,是一個(gè)支持網(wǎng)頁瀏覽器進(jìn)行實(shí)時(shí)語音對話或視頻對話的API。它于2011年6月1日開源并在Google、MozillaOpera支持下被納入萬維網(wǎng)聯(lián)盟的W3C推薦標(biāo)準(zhǔn)。

webRTC 是HTML 5 的一個(gè)擴(kuò)展,允許去獲取當(dāng)前客戶端的IP地址,可以查看當(dāng)前網(wǎng)址:net.ipcalf.com/

但如果使用 chrome 瀏覽器打開,此時(shí)可能會看到一串類似于:

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

的機(jī)器碼,這是因?yàn)?strong>chrome 默認(rèn)是隱藏掉 內(nèi)網(wǎng)IP地址的,可以通過修改 chrome 瀏覽器的配置更改此行為:

1、在chrome 瀏覽器地址欄中輸入:chrome://flags/

2、搜索 #enable-webrtc-hide-local-ips-with-mdns 該配置 并將屬性改為disabled

3、點(diǎn)擊relaunch 瀏覽器即可查看到本機(jī)的內(nèi)網(wǎng)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了
注意:記得一定要確保用戶的瀏覽器要經(jīng)過第一步的設(shè)置,不然可能就無法拿到了,且該方法只測試了谷歌瀏覽器

后臺解決方法

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;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容