Foro de elhacker.net

Programación => Desarrollo Web => Mensaje iniciado por: el-brujo en 27 Enero 2015, 17:31 pm



Título: Obtener la ip local y remota usando javascript
Publicado por: el-brujo en 27 Enero 2015, 17:31 pm
Get local and public IP addresses in javascript (github.com)
https://github.com/diafygi/webrtc-ips

Usando WebRTC


Código
  1. //get the IP addresses associated with an account
  2. function getIPs(callback){
  3.    var ip_dups = {};
  4.  
  5.    //compatibility for firefox and chrome
  6.    var RTCPeerConnection = window.RTCPeerConnection
  7.        || window.mozRTCPeerConnection
  8.        || window.webkitRTCPeerConnection;
  9.    var mediaConstraints = {
  10.        optional: [{RtpDataChannels: true}]
  11.    };
  12.  
  13.    //firefox already has a default stun server in about:config
  14.    //    media.peerconnection.default_iceservers =
  15.    //    [{"url": "stun:stun.services.mozilla.com"}]
  16.    var servers = undefined;
  17.  
  18.    //add same stun server for chrome
  19.    if(window.webkitRTCPeerConnection)
  20.        servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};
  21.  
  22.    //construct a new RTCPeerConnection
  23.    var pc = new RTCPeerConnection(servers, mediaConstraints);
  24.  
  25.    //listen for candidate events
  26.    pc.onicecandidate = function(ice){
  27.  
  28.        //skip non-candidate events
  29.        if(ice.candidate){
  30.  
  31.            //match just the IP address
  32.            var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/
  33.            var ip_addr = ip_regex.exec(ice.candidate.candidate)[1];
  34.  
  35.            //remove duplicates
  36.            if(ip_dups[ip_addr] === undefined)
  37.                callback(ip_addr);
  38.  
  39.            ip_dups[ip_addr] = true;
  40.        }
  41.    };
  42.  
  43.    //create a bogus data channel
  44.    pc.createDataChannel("");
  45.  
  46.    //create an offer sdp
  47.    pc.createOffer(function(result){
  48.  
  49.        //trigger the stun server request
  50.        pc.setLocalDescription(result, function(){});
  51.  
  52.    }, function(){});
  53. }
  54.  
  55. //Test: Print the IP addresses into the console
  56. getIPs(function(ip){console.log(ip);});