因项目需要,需要在app中获取客户的内网IP地址,使用js实现,经测试发现,在hbulider上的app获取ip地址时,如果切换无线网络,再获取不生效,还是上次连接的无线网ip,必须关闭软件清除手机缓存后才生效,同理,在手机谷歌浏览器下测试就没有问题,现在贴出代码,给大家试一下,不知道是不是bug问题,还是我没有找到正确的方法:
<script>
getIPs(function(ip) {
if (ip.match(/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/)) {
alert(ip);
}
});
function getIPs(callback) {
var ip_dups = {};
//compatibility for firefox and chrome
var RTCPeerConnection = window.RTCPeerConnection
|| window.mozRTCPeerConnection
|| window.webkitRTCPeerConnection;
var mediaConstraints = {
optional: [{RtpDataChannels: true}]
};
//firefox already has a default stun server in about:config
// media.peerconnection.default_iceservers =
var servers = undefined;
//add same stun server for chrome
if (window.webkitRTCPeerConnection)
servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};
//construct a new RTCPeerConnection
var pc = new RTCPeerConnection(servers, mediaConstraints);
//listen for candidate events
pc.onicecandidate = function(ice) {
//skip non-candidate events
if (ice.candidate) {
//match just the IP address
var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/;
var ip_addr = ip_regex.exec(ice.candidate.candidate)[1];
//remove duplicates
if (ip_dups[ip_addr] === undefined)
callback(ip_addr);
ip_dups[ip_addr] = true;
}
};
//create a bogus data channel
pc.createDataChannel("");
//create an offer sdp
pc.createOffer(function(result) {
//trigger the stun server request
pc.setLocalDescription(result, function() {
});
}, function() {
});
}
</script>