繁体   English   中英

在Safari上使用Javascript获取客户端IP地址

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM