通过js【获取电脑IP地址】🔈🔉🔊

477 阅读1分钟

使用第三方API获取

如新浪api,略。。。。。。

巧用webRTC

实测有效,当受限于浏览器,极其不稳定,不建议使用

实现

//获取用户本地ip的方法
    const getUserIP = onNewIP => {
      let MyPeerConnection =
        window.RTCPeerConnection ||
        window.mozRTCPeerConnection ||
        window.webkitRTCPeerConnection;
      let pc = new MyPeerConnection({
        iceServers: []
      });
      let noop = () => { };
      let localIPs = {};
      let ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
      let iterateIP = ip => {
        if (!localIPs[ip]) onNewIP(ip);
        localIPs[ip] = true;
      };
      pc.createDataChannel("");
      pc.createOffer()
        .then(sdp => {
          sdp.sdp.split("\n").forEach(function (line) {
            console.log(4 - 1);
            if (line.indexOf("candidate") < 0) return;
            console.log(4 - 2);
            line.match(ipRegex).forEach(iterateIP);
          });
          pc.setLocalDescription(sdp, noop, noop);
        })
        .catch(reason => { });
      pc.onicecandidate = ice => {
        if (
          !ice ||
          !ice.candidate ||
          !ice.candidate.candidate ||
          !ice.candidate.candidate.match(ipRegex)
        )
          return;
        ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
      };
    };

    //调用
    getUserIP(ip => {
      console.log("ip:", ip);
    });

详情传送门

js获取本机ip地址