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.