本地ip獲取
var findIP = new Promise(r=>{var w=window,a=new (w.RTCPeerConnection||w.mozRTCPeerConnection||w.webkitRTCPeerConnection)({iceServers:[]}),b=()=>{};a.createDataChannel("");a.createOffer(c=>a.setLocalDescription(c,b,b),b);a.onicecandidate=c=>{try{c.candidate.candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g).forEach(r)}catch(e){console.log(e)}}})
/*Usage example*/
findIP.then(ip => document.write('your ip: ', ip)).catch(e => console.error(e))
- 如果candidate.match的報錯或者無值,是因為谷歌對本地ip進(jìn)行編碼,變成了2e5a...2e5a.local的形式,要開放谷歌瀏覽器的功能,才能得到值,所以如果應(yīng)用場景不在瀏覽器可控的情形下不可采用此方式。
- 谷歌上輸入 chrome://flags/
- 搜索#enable-webrtc-hide-local-ips-with-mdns
- 設(shè)置此項為 disable
參考連接