前端获取IP

广告位招租
扫码页面底部二维码联系

在前端js代码中获取用户的IP地址:

export function getUserIP() {
  return new Promise((resolve, reject) => {
    const RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
    const pc = new RTCPeerConnection({
      iceServers: []
    })
    const noop = function() {}
    const localIPs = {}
    const ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g
    const iterateIP = (ip) => {
      if (!localIPs[ip]) {
        resolve(ip)
      }
      localIPs[ip] = true
    }

    //create a bogus data channel
    pc.createDataChannel('')
    // create offer and set local description
    try {
      pc.createOffer(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)
      }, function(sdp) {
        reject()
      })
    }
    catch (err) {
      reject(err)
    }
    //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)
    }
  })
}

需要用到webRTC,如果不支持该接口,那就无法获取。