0

Holas esta es mi primera pregunta ojala se entienda, estoy intentando obtener la IP local (interna o PC cliente) con JavaScript, cuando me decidí hacer esto, encontré un códigos que me funcionaba de maravilla (primer código), luego se actualizo chrome y dejo de funcionar, intente arreglarlo pero la verdad es que no pude, por lo cual busque otro código (segundo código), el cual funciono excelente en Firefox y Chrome (navegadores que me interesa que funcione), pero despues de una actualización nuevamente fallo en Chrome y hace poco ambos métodos fallan en Firefox. Yo la verdad es que no entiendo mucho de WebRTC, se que se utiliza para obtener la ip local (e buscado información pero no llego a nada muy concreto la verdad XD), si alguien me pudiera orientar donde buscar o como corregir estos problemas o si conocen otro método para hacerlo, de antemano muchas gracias.

primer código

    function getIPs(callback){
            var ip_dups = {};

            //compatibility for firefox and chrome
            var RTCPeerConnection = window.RTCPeerConnection
                || window.mozRTCPeerConnection
                || window.webkitRTCPeerConnection;
            var useWebKit = !!window.webkitRTCPeerConnection;

            //bypass naive webrtc blocking using an iframe
            if(!RTCPeerConnection){
                //NOTE: you need to have an iframe in the page right above the script tag
                //
                //<iframe id="iframe" sandbox="allow-same-origin" style="display: none"></iframe>
                //<script>...getIPs called in here...
                //
                var win = iframe.contentWindow;
                RTCPeerConnection = win.RTCPeerConnection
                    || win.mozRTCPeerConnection
                    || win.webkitRTCPeerConnection;
                useWebKit = !!win.webkitRTCPeerConnection;
            }

            //minimal requirements for data connection
            var mediaConstraints = {
                optional: [{RtpDataChannels: true}]
            };

            var servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};

            //construct a new RTCPeerConnection
            var pc = new RTCPeerConnection(servers, mediaConstraints);

            function handleCandidate(candidate){
                //match just the IP address
                var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
                var ip_addr = ip_regex.exec(candidate)[1];

                //remove duplicates
                if(ip_dups[ip_addr] === undefined)
                    callback(ip_addr);

                ip_dups[ip_addr] = true;
            }

            //listen for candidate events
            pc.onicecandidate = function(ice){

                //skip non-candidate events
                if(ice.candidate)
                    handleCandidate(ice.candidate.candidate);
            };

            //create a bogus data channel
            pc.createDataChannel("");

            //create an offer sdp
            pc.createOffer(function(result){

                //trigger the stun server request
                pc.setLocalDescription(result, function(){}, function(){});

            }, function(){});

            //wait for a while to let everything done
            setTimeout(function(){
                //read candidate info from local description
                var lines = pc.localDescription.sdp.split('\n');

                lines.forEach(function(line){
                    if(line.indexOf('a=candidate:') === 0)
                        handleCandidate(line);
                });
            }, 1000);
        }

        //insert IP addresses into the page
        getIPs(function(ip){
            var li = document.createElement("li");
            li.textContent = ip;

            //local IPs
            if (ip.match(/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/))
                document.getElementsByTagName("ul")[0].appendChild(li);

            //IPv6 addresses
            else if (ip.match(/^[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7}$/))
                document.getElementsByTagName("ul")[2].appendChild(li);

            //assume the rest are public IPs
            else
                document.getElementsByTagName("ul")[1].appendChild(li);
        });

Problema: Uncaught TypeError: Cannot read property 'sdp' of null

Linea de error: var lines = pc.localDescription.sdp.split('\n');

pagina de prueba = https://diafygi.github.io/webrtc-ips/

Segundo código

    var RTCPeerConnection = /*window.RTCPeerConnection ||*/ window.webkitRTCPeerConnection || window.mozRTCPeerConnection;

    if (RTCPeerConnection) (function () {
        var rtc = new RTCPeerConnection({ iceServers: [] });
        if (1 || window.mozRTCPeerConnection) {
            rtc.createDataChannel('', { reliable: false });
        };
        rtc.onicecandidate = function (evt) {
            if (evt.candidate) grepSDP("a=" + evt.candidate.candidate);
        };
        rtc.createOffer(function (offerDesc) {
            grepSDP(offerDesc.sdp);
            rtc.setLocalDescription(offerDesc);
        }, function (e) { console.warn("offer failed", e); });
        var addrs = Object.create(null);
        addrs["0.0.0.0"] = false;
        function updateDisplay(newAddr) {
            if (newAddr in addrs) return;
            else addrs[newAddr] = true;
            var displayAddrs = Object.keys(addrs).filter(function (k) { return addrs[k]; });
            myIP = displayAddrs.join(" or perhaps ") || "n/a";
        }
        function grepSDP(sdp) {
            var hosts = [];
            sdp.split('\r\n').forEach(function (line) {
                if (~line.indexOf("a=candidate")) {
                    var parts = line.split(' '),
                        addr = parts[4],
                        type = parts[7];
                    if (type === 'host') updateDisplay(addr);
                } else if (~line.indexOf("c=")) {
                    var parts = line.split(' '),
                        addr = parts[2];
                    updateDisplay(addr);
                }
            });
        }
    })(); else {
        myIP = "";
    }

Problema: no devuelve un error, pero muestra de esta forma la ip 6a3f6fb1-14b2-4631-a4ff-9059695588a8.local

4
  • Ten en cuenta que RTCPeerConnection aún es experimental, algo que funciona ahora puede que no funcione en la siguiente actualización y que vuelva a funcionar para otra, esto considerando que por razones de seguridad quizás nunca se implemente una funcionalidad que obtenga la IP local, pero si hallas la respuesta no olvides postearla acá.
    – Vlady
    el 10 mar. 2020 a las 22:40
  • 1
    ¿Responde esto a tu pregunta? Como obtener la IP o nombre del equipo con JavaScript
    – fredyfx
    el 10 mar. 2020 a las 22:42
  • es.stackoverflow.com/a/46438/822
    – fredyfx
    el 10 mar. 2020 a las 22:42
  • @fredyfx el enlace que me envías es el mismo que yo puse como primer código, antes funcionaba excelente pero ahora ya no me funciona, pero muchas gracias por responder
    – doger
    el 11 mar. 2020 a las 13:11

0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

Examina otras preguntas con la etiqueta o formula tu propia pregunta.