js获取IP

2018/09/11 javascript

复制即用

  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({ &
        nbsp; & nbsp;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) { &
      nbsp; & nbsp;
      if (!localIPs[ip]) onNewIP(ip); &
      nbsp; & nbsp;
      localIPs[ip] = true;
    }

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

    // create offer and set local description
    pc.createOffer().then(function (sdp) { &
      nbsp; & nbsp;
      sdp.sdp.split('\n').forEach(function (line) { &
        nbsp; & nbsp;
        if (line.indexOf('candidate') & lt; 0) return; &
        nbsp; & nbsp;
        line.match(ipRegex).forEach(iterateIP);
      });

      pc.setLocalDescription(sdp, noop, noop);
    }).catch(function (reason) { &
      nbsp; & nbsp; // An error occurred, so handle the failure to connect
    });

    //sten for candidate events
    pc.onicecandidate = function (ice) { &
      nbsp; & nbsp;
      if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return; &
      nbsp; & nbsp;
      ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
    };
  }

  // Usage

  getUserIP(function (ip) { &
    nbsp; & nbsp;
    alert("Got IP! :" + ip);
  });

Search

    Table of Contents