首页 > 解决方案 > 使用带有 chrome 的 Javascript 获取本地 IP 返回哈希/主机名

问题描述

我正在使用此代码https://ourcodeworld.com/articles/read/257/how-to-get-the-client-ip-address-with-javascript-only允许在浏览器中获取本地 IP(Chrome在我的情况下)使用ice.candidate,但在某些情况下它不会返回IP,而是返回一种主机名(例如“0ddcdf5f-6ba6-47fb-8183-e44f51a1afc7.local”)。我还没有找到真正的原因,因为有时它不起作用。

我也没有找到替代方案。

这是一个测试https://jsfiddle.net/42g5jzpx/,在我的计算机上运行良好,但在其他计算机上运行良好,返回上面的主机名。

/**
 * 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);
});

谢谢

保罗

标签: javascript

解决方案


谢谢你的问题。

我了解您的尝试,但请在 JSFiddle 或其他上分享您的尝试。

根据我的经验,我使用db-ip.com了 api,它工作得非常好。

检查DBIP

谢谢


推荐阅读