-4

I'm using this code https://ourcodeworld.com/articles/read/257/how-to-get-the-client-ip-address-with-javascript-only that allow to get local IP within a browser (Chrome in my case) using ice.candidate, but in some situation it doesn't return the IP but a sort of hostname (for example "0ddcdf5f-6ba6-47fb-8183-e44f51a1afc7.local"). I haven't found a real reason because sometimes it works other not.

I didn't found an alternative either.

Here a test https://jsfiddle.net/42g5jzpx/, works fine in my computer but not in others, returning the hostname above.

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

Thanks

Paolo

2 Answers2

1

Thanks for your question.

I understand how you tried but please share your tries on JSFiddle or other.

In my experience, I used db-ip.com api and it works really fine.

Check DBIP

Thanks

George Wang
  • 451
  • 2
  • 12
0

I found the solution as specified here : Google Chrome hide local IP by default. It shows something similar to e87e041d-15e1-4662-adad-7a6601fca9fb.local . This behaviour can be changes by setting the variable #enable-webrtc-hide-local-ips-with-mdns to disabled in Chrome://flags