[英]Get the client IP address with Javascript on Safari
由於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
沒有定義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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.