本地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进行编码,变成了2e5a...2e5a.local的形式,要开放谷歌浏览器的功能,才能得到值,所以如果应用场景不在浏览器可控的情形下不可采用此方式。
- 谷歌上输入 chrome://flags/
- 搜索#enable-webrtc-hide-local-ips-with-mdns
- 设置此项为 disable
参考连接