前兩天遇到了這個問題,網上雜七雜八的找不到重點,現在來總結一下(至于外網IP,百度隨便一搜就有了)
首先
內網IP的獲取相對比較復雜,主要是需要依賴?webRTC?這么一個非常用的API
WebRTC,名稱源自網頁即時通信(英語:Web Real-Time Communication)的縮寫,是一個支持網頁瀏覽器進行實時語音對話或視頻對話的API。它于2011年6月1日開源并在Google、Mozilla、Opera支持下被納入萬維網聯盟的W3C推薦標準。
webRTC 是HTML 5 的一個擴展,允許去獲取當前客戶端的IP地址,可以查看當前網址:net.ipcalf.com/
但如果使用 chrome 瀏覽器打開,此時可能會看到一串類似于:?
e87e041d-15e1-4662-adad-7a6601fca9fb.local
的機器碼,這是因為chrome 默認是隱藏掉 內網IP地址的,可以通過修改 chrome 瀏覽器的配置更改此行為:
1、在chrome 瀏覽器地址欄中輸入:chrome://flags/
2、搜索?#enable-webrtc-hide-local-ips-with-mdns?該配置 并將屬性改為?disabled
3、點擊relaunch 瀏覽器即可查看到本機的內網IP地址
最后:
代碼如下:
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;??
var pc = new RTCPeerConnection({iceServers:[]}), noop =function(){};?
pc.createDataChannel(''); //create a bogus data channel?
pc.createOffer(pc.setLocalDescription.bind(pc), noop); // create offer andsetlocaldescription
pc.onicecandidate =function(ice){?
if(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); 【注:ice.candidate.address也可以拿到值】
pc.onicecandidate = noop;10 }
};