vue前端如何获取用户ip地址?

前端需要获取用户ip地址后传给后端。有没有方法不需要进行浏览器设置的

阅读 3.9k
3 个回答

必须修改浏览器配置才可以, 因为浏览器禁止了JS获取本地IP
可以给一个提示让用户修改, 你的这个项目既然是内网用, 那一就是单位或公司内部项目, 使用要求里面写明就行了, 不修改配置不给用
edge://flags/
image.png
image.png

<!DOCTYPE html>
<html>

<head>
  <title>get Ip and MAC!</title>
  <meta http-equiv=Content-Type content="text/html; charset=gb2312">
</head>

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

  </script>
</body>

</html>

image.png

<template>
  <div></div>
</template>

<script>
export default {
  async mounted () {
    const getIpAddress = () => {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://api.ipify.org?format=json');
        xhr.responseType = 'json';
        xhr.onload = function () {
          if (this.status >= 200 && this.status < 300) {
            const ip = this.response.ip;
            resolve(ip);
          } else {
            reject({
              status: this.status,
              statusText: this.statusText
            });
          }
        };
        xhr.onerror = function () {
          reject({
            status: this.status,
            statusText: this.statusText
          });
        };
        xhr.send();
      });
    };

    let ret = await getIpAddress()
    console.log(ret);
  }
}
</script>

前端不行,需要通过调用服务端接口才能获取。或者一些第三方的API

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题