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

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

相关推荐
AI周红伟16 分钟前
Agent Skills生产级Skills 案例实操-周红伟
前端·chrome·react.js·langchain
Java编程爱好者23 分钟前
Spring AI 1.0 实战:从原理到落地的完整指南
javascript
我命由我1234534 分钟前
VSCode - VSCode 自定义折叠区域
前端·javascript·ide·vscode·前端框架·编辑器·js
清水白石0081 小时前
Python 数据建模指南:dataclass、TypedDict 与 Pydantic 的选型博弈
前端·javascript·python
ZC跨境爬虫1 小时前
跟着 MDN 学CSS day_23:(表单与表格综合样式化实战)
前端·javascript·css·ui·html·tensorflow
MRSM_011 小时前
Three.js 入门:在浏览器里构建你的第一个 3D 场景
javascript
超人气王1 小时前
JavaScript新手基础入门——this指针指向,一文带你搞清楚
前端·javascript
z落落1 小时前
C# 数组属性和方法(Clear / Copy / IndexOf / LastIndexOf)
开发语言·javascript·c#
嘟嘟07171 小时前
Python切片技巧×DeepSeek API:手把手教你打造智能商品文案生成器
前端·javascript
月月大王的3D日记1 小时前
Three.js Day 4:材质初探(上)——Basic、Normal、Matcap、Depth 一口气认识四种
javascript