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

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

相关推荐
随风一样自由17 小时前
【前端+跨端技术新格局】Tauri vs Electron 完整性能对比(2026实测数据+底层原理)
前端·javascript·electron
Reload.18 小时前
GJ航司,验证码网易易盾 JS逆向 纯算轨迹
开发语言·前端·javascript
铁皮饭盒18 小时前
Bun.js 集成了 SQL/Redis/S3,为什么 Java/Go/Python 不集成?
javascript
年轻的砖头18 小时前
以Ajax方式提交整个表单
前端·javascript·ajax
L-影18 小时前
FastAPI CORS 跨域:Web 世界的“小区门禁”与“访客通行证”
前端·javascript·fastapi
Dxy12393102161 天前
MySQL索引完整教程:创建、查看、修改、删除与日常管理
前端·javascript·mysql
端庄的战斗机1 天前
javascript 设计模式(文章很长,请自备瓜子,水果和眼药水)
开发语言·javascript·设计模式
前端毕业班1 天前
uni-app 小程序支持 teleport 了
前端·javascript·vue.js
东风破_1 天前
LLM 为什么记不住你?无状态、messages 和上下文管理
javascript·人工智能
Hilaku1 天前
前端架构师的克制:什么时候该坚决对新技术说不?
前端·javascript·程序员