前端解決方法
首先
內(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、Mozilla、Opera支持下被納入萬維網(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;