自从 Safari 更新到版本 11 以来,我们可以使用 WebRTC API。但是,我试图获取客户端IP地址(本地IP,即192.168.1.10),但没有结果。
我正在使用的代码是您可以在多个指南中找到的代码。相同的代码适用于 Chrome 和 Firefox,它们比 Safari 更早兼容此 API。事情是这样的:
/**
* Get the user IP throught the webkitRTCPeerConnection
* @param onNewIP {Function} listener function to expose the IP locally
* @return undefined
*/
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
});
//listen 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);
};
}
// Usage
getUserIP(function(ip){
alert("Got IP! :" + ip);
});
我一直在调试,发现 ice.candidate
未定义,因此代码中没有任何 IP 可供迭代。
有什么想法或替代方案吗?
谢谢。
最佳答案
Safari 正在实现最新版本的规范,出于安全原因,该规范将阻止生成本地候选者。您可以在浏览器中选择一个选项,允许您授予 safari 执行此操作的权限,但需要手动完成。其他浏览器尚未完全兼容,但仍允许生成本地候选。
在开发者菜单中,您可以选择停止过滤候选人。 https://i1.wp.com/webrtcbydralex.com/wp-content/uploads/2017/06/Screen-Shot-2017-06-16-at-3.20.30-PM.png
关于javascript - 在 Safari 上使用 Javascript 获取客户端 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46925857/