背景
項目中的sass 系統(tǒng)有多種用戶權(quán)限,且同一個帳號可以多個人同時登錄,導(dǎo)致有些操作無法直接追溯到對應(yīng)的責(zé)任人,因此需要獲取到當(dāng)前登錄用戶的IP地址(員工內(nèi)部人員的內(nèi)網(wǎng)地址)并收集上報。
如何收集
1. 公網(wǎng)IP
對于收集公網(wǎng)IP, 目前通用的是利用新浪和搜狐 的接口,可兼容多種瀏覽器。對于一些使用如ActiveX 等IE特有的API不做介紹,要想了解請轉(zhuǎn):https://www.cnblogs.com/zhangycun/p/7339346.html
搜狐接口:
<scriptsrc="http://pv.sohu.com/cityjson?ie=utf-8"></script>? <scripttype="text/javascript">3document.write(returnCitySN["cip"]+','+returnCitySN["cname"])
// 110.87.118.246,福建省廈門市4</script>
新浪接口:
<scripttype="text/javascript"src="http://counter.sina.com.cn/ip/"charset="gb2312"></script>? ? ? <!--獲取接口數(shù)據(jù),注意charset -->
<scripttype="text/javascript">
document.writeln("IP地址:"+ILData[0]+"<br />");//輸出接口數(shù)據(jù)中的IP地址 4document.writeln("地址類型:"+ILData[1]+"<br />");//輸出接口數(shù)據(jù)中的IP地址的類型 5document.writeln("地址類型:"+ILData[2]+"<br />");//輸出接口數(shù)據(jù)中的IP地址的省市6document.writeln("地址類型:"+ILData[3]+"<br />");//輸出接口數(shù)據(jù)中的IP地址的7document.writeln("地址類型:"+ILData[4]+"<br />");//輸出接口數(shù)據(jù)中的IP地址的運營商8</script>
缺點:依賴與搜狐和新浪的服務(wù)器穩(wěn)定性,如果資源所在的服務(wù)器掛了,就無法獲取到對應(yīng)的IP
2. 內(nèi)網(wǎng)IP
內(nèi)網(wǎng)IP的獲取相對比較復(fù)雜,主要是需要依賴 webRTC 這么一個非常用的API
WebRTC,名稱源自網(wǎng)頁即時通信(英語:Web Real-Time Communication)的縮寫,是一個支持網(wǎng)頁瀏覽器進行實時語音對話或視頻對話的API。它于2011年6月1日開源并在Google、Mozilla、Opera支持下被納入萬維網(wǎng)聯(lián)盟的W3C推薦標(biāo)準(zhǔn)。
webRTC 是HTML 5 的一個擴展,允許去獲取當(dāng)前客戶端的IP地址,可以查看當(dāng)前網(wǎng)址:http://net.ipcalf.com/
如果使用 chrome 瀏覽器打開,此時可能會看到一串類似于:`e87e041d-15e1-4662-adad-7a6601fca9fb.local? 的機器碼,這是因為chrome 默認(rèn)是隱藏掉 內(nèi)網(wǎng)IP地址的,可以通過修改 chrome 瀏覽器的配置更改此行為:
在chrome 瀏覽器地址欄中輸入:chrome://flags/
搜索#enable-webrtc-hide-local-ips-with-mdns 該配置 并將屬性改為?disabled
relaunch 瀏覽器即可查看到本機的內(nèi)網(wǎng)IP地址

獲取內(nèi)網(wǎng)的js 代碼: 源碼:webrtc-ips
window.RTCPeerConnection=window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection;//compatibility for Firefox and chrome
var pc=newRTCPeerConnection({iceServers:[]}),noop=function(){};
pc.createDataChannel('');//create a bogus data channel pc.createOffer(pc.setLocalDescription.bind(pc),noop);// create offer and set local description pc.onicecandidate=function(ice){ 6if(ice&&ice.candidate&&ice.candidate.candidate){
var myIP=/([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1]; console.log('my IP: ',myIP);
pc.onicecandidate=noop; }
};