javascript 获取本机ip chrome 谷歌浏览器 extension 谷歌扩展

代码一:

javascript 复制代码
  if (typeof window != 'undefined') {
    var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
    if (RTCPeerConnection)(() => {
      var rtc = new RTCPeerConnection()
      rtc.createDataChannel(''); //创建一个可以发送任意数据的数据通道
      rtc.createOffer(offerDesc => { //创建并存储一个sdp数据
        rtc.setLocalDescription(offerDesc)
      }, e => {
        console.log(e)
      })
 
      rtc.onicecandidate = (evt) => { //监听candidate事件
        if (evt.candidate) {
          console.log('evt:', evt.candidate)
          let ip_rule = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
          var ip_addr = ip_rule.exec(evt.candidate.candidate)[1]
          console.log('ip_addr:', ip_addr) //打印获取的IP地址
        }
      }
    })()
    else {
      console.log("没有找到")
    }
  }

代码二:

javascript 复制代码
function getLocalIPs(callback) {
var ips = [];

var RTCPeerConnection = window.RTCPeerConnection ||
  window.webkitRTCPeerConnection || window.mozRTCPeerConnection;

var pc = new RTCPeerConnection({
  // Don't specify any stun/turn servers, otherwise you will
  // also find your public IP addresses.
  iceServers: []
});
// Add a media line, this is needed to activate candidate gathering.
pc.createDataChannel('');

// onicecandidate is triggered whenever a candidate has been found.
pc.onicecandidate = function (e) {
  if (!e.candidate) { // Candidate gathering completed.
    pc.close();
    callback(ips);
    return;
  }
  var ip = /^candidate:.+ (\S+) \d+ typ/.exec(e.candidate.candidate)[1];
  if (ips.indexOf(ip) == -1) // avoid duplicate entries (tcp/udp)
    ips.push(ip);
};
pc.createOffer(function (sdp) {
  pc.setLocalDescription(sdp);
}, function onerror() {});
}

如果获取到的格式为:xxxx-xxxx-xxxx-xxxx.local,则需要改下chrome的设置(默认隐藏了本机ip)

搜索chrome://flags/#enable-webrtc-hide-local-ips-with-mdns

将Anonymize local IPs exposed by WebRTC置为disabled

听说有些版本没有这个设置,那就得再继续找方案了~

相关推荐
其美杰布-富贵-李1 小时前
第 10 篇:灯光与阴影
javascript·three.js
小高0073 小时前
🔥🔥🔥TypeScript 7 正式版来了:别只看 10 倍速度,这 4 个迁移坑更值得注意
前端·javascript·面试
di24k24k4 小时前
多个 el-form 共用同一 ref 导致表单校验部分失效
前端·javascript·vue.js·elementui
JKooll4 小时前
WPS 表格 DISPIMG 函数实战:用 JavaScript 将图片真正嵌入单元格
javascript·wps
晴天165 小时前
Rust 快速入门 (从 JavaScript 开发者视角)-Day09
开发语言·javascript·rust
其美杰布-富贵-李5 小时前
第 6 篇:相机与 OrbitControls
前端·javascript·three.js
Hilaku6 小时前
当 AI 一天写完一周的代码,我们还剩什么优势?
前端·javascript·程序员
无责任此方_修行中6 小时前
换个版本号就能升级?可没那简单:pnpm 11 升级踩坑记
javascript·后端·npm
尘世中一位迷途小书童6 小时前
无人机航线里的云台角度怎么调?Cesium 做了个视锥 + 鹰眼联动
前端·javascript·数据可视化
张元清7 小时前
React useMeasure Hook:用 ResizeObserver 测量 DOM 元素 (2026)
javascript·react.js