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

时间:2017-10-25 06:55:33

标签: javascript webrtc

由于Safari已更新至版本11,因此我们可以使用WebRTC API。但是,我正在尝试获取客户端IP地址(本地IP,即192.168.1.10),但没有结果。

我正在使用的代码是您可以在多个指南中找到的代码。相同的代码适用于Chrome和Firefox,它们之前与Safari兼容。它是这样的:

 /**
 * 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可以在代码中进行迭代。

任何想法或替代方案?

谢谢。

1 个答案:

答案 0 :(得分:1)

Safari正在实施该规范的最新版本,出于安全原因,该版本会阻止生成本地候选项。您在浏览器中有一个选项,允许您为safari提供执行权限,但需要手动完成。其他浏览器尚未完全兼容,仍然允许生成本地候选者。

在开发者菜单中,您可以选择停止过滤候选人。 https://i1.wp.com/webrtcbydralex.com/wp-content/uploads/2017/06/Screen-Shot-2017-06-16-at-3.20.30-PM.png