function getUserIP(onNewIP) { // onNewIp - your listener function for new IPs
console.log('enter...');
//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) {
console.log('reson:' + reason);
// An error occurred, so handle the failure to connect
});
//listen for candidate events
pc.onicecandidate = function(ice) {
console.log('ice: ' + ice);
ace = ice;
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) {
console.log('not');
return;
}
ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
};
}
getUserIP(function(myIp) {
alert(myIp)
})
页面使用如上的代码获取客户端内网IP。部署在部分阿里云机器上时,浏览器访问这个页面,会无法往下执行,页面卡住!但是在部分机器(或者本机)时,页面可以正常渲染完成。
服务器应该只是把页面返回,解析过程是浏览器引擎完成的,为什么还会出现部署不同服务器,访问后效果不同?
谷歌浏览器打开
chrome://flags/
搜索enable-webrtc-hide-local-ips-with-mdns
需要设置为disable
否则是看不到IP的。