JS获取用户IP地址

const getIPs = (callback) => {
    var ip_dups = {};
    var RTCPeerConnection = window.RTCPeerConnection
      || window.mozRTCPeerConnection
      || window.webkitRTCPeerConnection;
    var useWebKit = !!window.webkitRTCPeerConnection;
    var mediaConstraints = {
      optional: [{ RtpDataChannels: true }]
    };
    // 这里就是需要的ICEServer了
    var servers = {
      iceServers: [
        { urls: "stun:stun.services.mozilla.com" },
        { urls: "stun:stun.l.google.com:19302" },
      ]
    };
    var pc = new RTCPeerConnection(servers, mediaConstraints);
    function handleCandidate(candidate) {
      var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
      var hasIp = ip_regex.exec(candidate)
      if (hasIp) {
        var ip_addr = ip_regex.exec(candidate)[1];
        if (ip_dups[ip_addr] === undefined)
          callback(ip_addr);
        ip_dups[ip_addr] = true;
      }
    }
    // 网络协商的过程
    pc.onicecandidate = function (ice) {
      if (ice.candidate) {
        handleCandidate(ice.candidate.candidate);
      }
    };
    pc.createDataChannel("");
    //创建一个SDP(session description protocol)会话描述协议 是一个纯文本信息 包含了媒体和网络协商的信息
    pc.createOffer(function (result) {
      pc.setLocalDescription(result, function () { }, function () { });
    }, function () { });
    setTimeout(function () {
      var lines = pc.localDescription.sdp.split('\n');
      lines.forEach(function (line) {
        if (line.indexOf('a=candidate:') === 0)
          handleCandidate(line);
      });
    }, 1000);
  }
使用
getIPs((ip) => {
  console.log('ip', ip)
});
  • 6
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值