JS獲取本地IP&顯示隱藏IP
前言
這段時間一直在搞前端,我一個軟件開發工程師開發前端得多閒.項目需求需要獲取當前機器IP,所以從網上搜索一堆代碼摘除來加到項目中,其中遇到的問題在下面已經加上了,方便回顧.
JS獲取本地IP方法
代碼如下:
function getUserIP(onNewIP) { // onNewIp - your listener function for new IPs
//compatibility for firefox and chrome
var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var pc = new myPeerConnection({
iceServers: []
}),
noop = function() {},
localIPs = {},
ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
key;
function iterateIP(ip) {
if (!localIPs[ip]) onNewIP(ip);
localIPs[ip] = true;
}
//create a bogus data channel
pc.createDataChannel("");
// create offer and set local description
pc.createOffer().then(function(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(function(reason) {
// An error occurred, so handle the failure to connect
});
//sten for candidate events
pc.onicecandidate = function(ice) {
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
};
}
遇到問題
代碼寫好了,查看IP可以查到,但出現一次問題如下描述:
針對對ice的打印看到其中candiate出現類似如下提示:
UDP ... e94a0c1d-1431-dec2-acda-74e61efc29b3.local
本來.local的位置應該是IP,類似"172.16.22.21",但是出現.local
搜索問題發現如下信息,
JS大法 - 純JS 獲取客戶端IP地址,
RTCIceCandidate.candidate,
webrtc candidate xxx.local mDNS ip地址問題.
所以,爲了能顯示當前IP,提出如下解決方案
解決方案
火狐(FireFox)刪除隱藏IP
打開IPabout:config
搜索配置media.peerconnection.ice.obfuscate_host_addresses
改爲false
此時刷新程序,IP正常顯示
谷歌(Chrome)刪除隱藏IP
在chrome 瀏覽器地址欄中輸入:chrome://flags/
搜索#enable-webrtc-hide-local-ips-with-mdns
該配置 並將屬性改爲 disabled
此時刷新程序,IP正常顯示.
浪費一天時間,只爲了這一個Bug.