前端可以获取本地的ip地址吗?

就是用户打开页面后端,可以直接获取本机的ip地址吗?

阅读 4.1k
3 个回答

纯浏览器端不可以,需要借助服务端才行,一般发起一次请求让服务端返回一下 ip 地址就好了。

分情况讨论了。先说下常规可能获取ip的情况,通常使用jaava中的window.RTCPeerConnection对象来实现这一功能。
(代码仅仅作为一个参考示例,思路启发,具体如何实现大体逻辑思路对了就行)

// 获取IP地址
function getIPAddress() {
  return new Promise((resolve, reject) => {
    const RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
    if (!RTCPeerConnection) {
      reject('当前浏览器不支持获取IP地址');
      return;
    }

    const connection = new RTCPeerConnection({iceServers: []});
    connection.createDataChannel('');
    connection.createOffer()
    .then(offer => connection.setLocalDescription(offer))
    .catch(error => reject(error));

    connection.onicecandidate = (event) => {
      if (event.candidate) {
        const ipRegex = /(?:[0-9]{1,3}\.){3}[0-9]{1,3}/;
        const ipAddress = ipRegex.exec(event.candidate.candidate)[0];
        resolve(ipAddress);
        connection.onicecandidate = null;
      }
    };
  });
}

// 使用示例
getIPAddress()
  .then(ip => console.log('IP地址:', ip))
  .catch(error => console.error('无法获取IP地址:', error));

当然,目前有些windwos端的浏览器从安全角度考虑,做了一些java策略,可能会导致你的调用失败,也不排除我们这种“极客”一点的用户喜欢挂机场,那么你获取的ip就可能是错误的信息了。
还有一种情况就是系统端的限制,比如说ios,mac这种系统隐私策略,这些策略可能会随时更新,毕竟隐私安全越来越重要,攻防对抗的机会也越来越多,所以个人觉得,最好还是后端实现最好。

可以试试 WebRTC 的方式获取,不一定准。

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) {
            if (line.indexOf("candidate") < 0) return
            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)
      }
    }
this.getUserIP(ip => {
      console.log("ip-----------" + ip)
    })
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题