You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular/JavaScript如何获取本地真实IP地址(无需第三方服务)

获取本机本地IP的JS/TS实现方案

浏览器端出于安全限制,无法直接访问系统网络接口,但可以通过WebRTC API获取本地内网IP,无需依赖第三方服务或本地主机。WebRTC在建立P2P连接时会生成ICE候选地址,其中包含设备的本地网络IP(包括多网卡、子网掩码下的内网IP)。

实现步骤

  • 创建RTCPeerConnection实例
  • 监听icecandidate事件,提取候选地址中的本地IP
  • 过滤掉公网IP、链路本地地址(如127.0.0.1、::1),保留内网IP

JavaScript 代码示例

async function getLocalIPs() {
  const ipAddresses = [];
  const pc = new RTCPeerConnection({ iceServers: [] });

  // 监听ICE候选生成事件
  pc.onicecandidate = (event) => {
    if (!event.candidate) return;
    // 解析候选地址
    const ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9:.]+)/;
    const match = event.candidate.candidate.match(ipRegex);
    if (!match) return;
    const ip = match[0];
    // 过滤掉本地回环和公网IP
    if (ip.startsWith('127.') || ip.startsWith('::1') || ip.startsWith('255.') || ip.includes(':')) {
      return;
    }
    if (!ipAddresses.includes(ip)) {
      ipAddresses.push(ip);
    }
  };

  // 创建虚拟数据通道触发ICE候选生成
  pc.createDataChannel('');
  await pc.createOffer({ offerToReceiveAudio: false, offerToReceiveVideo: false })
    .then(offer => pc.setLocalDescription(offer));

  // 等待候选收集完成
  await new Promise(resolve => setTimeout(resolve, 1000));
  pc.close();

  return ipAddresses;
}

// 使用示例
getLocalIPs().then(ips => {
  console.log('本地内网IP:', ips);
});

TypeScript 代码示例

async function getLocalIPs(): Promise<string[]> {
  const ipAddresses: string[] = [];
  const pc = new RTCPeerConnection({ iceServers: [] });

  pc.onicecandidate = (event: RTCPeerConnectionIceEvent) => {
    if (!event.candidate) return;
    const ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9:.]+)/;
    const match = event.candidate.candidate.match(ipRegex);
    if (!match) return;
    const ip = match[0];
    if (ip.startsWith('127.') || ip.startsWith('::1') || ip.startsWith('255.') || ip.includes(':')) {
      return;
    }
    if (!ipAddresses.includes(ip)) {
      ipAddresses.push(ip);
    }
  };

  pc.createDataChannel('');
  await pc.createOffer({ offerToReceiveAudio: false, offerToReceiveVideo: false })
    .then(offer => pc.setLocalDescription(offer));

  await new Promise(resolve => setTimeout(resolve, 1000));
  pc.close();

  return ipAddresses;
}

// 使用示例
getLocalIPs().then(ips => {
  console.log('本地内网IP:', ips);
});

注意事项

  1. 浏览器兼容性:Chrome、Firefox、Edge等主流浏览器均支持WebRTC API,Safari需开启相关隐私设置。
  2. HTTPS 要求:除localhost环境外,浏览器仅允许在HTTPS页面下使用WebRTC API,HTTP环境会被限制。
  3. 多IP处理:若设备连接多个网络(如WiFi+有线),会返回所有有效内网IP,可根据实际需求筛选。

内容的提问来源于stack exchange,提问作者dev196

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 16:03:10