当前位置: 首页 > news >正文

Electron 开发:获取当前客户端 IP

Electron 开发:获取当前客户端 IP

一、背景与需求

1. 项目背景

客户端会自启动一个服务,Web/后端服务通过 IP + port 请求以操作客户端接口

2. 初始方案与问题

2.1. 初始方案:通过代码获取本机 IP
/**
 * 获取局域网 IP
 * @returns {string} 局域网 IP
 */
export function getLocalIP(): string {
  const interfaces = os.networkInterfaces()
  for (const name of Object.keys(interfaces)) {
    for (const iface of interfaces[name] || []) {
      if (iface.family === 'IPv4' && !iface.internal) {
        log.info('获取局域网 IP:', iface.address)
        return iface.address
      }
    }
  }
  log.warn('无法获取局域网 IP,使用默认 IP: 127.0.0.1')
  return '127.0.0.1'
}
2.2. 遇到的问题

如果设备开启了代理,可能获取的是代理 IP,导致后端请求失败

二、解决方案设计

1. 总体思路

  • 获取本机所有 IP
  • 遍历 IP + port 请求客户端服务接口
  • 成功响应即为目标 IP
  • 缓存有效 IP,避免频繁请求

2. 获取所有可能的 IP

使用 Node.js 的 os.networkInterfaces() 获取所有可用 IP

private getAllPossibleIPs(): string[] {
  const interfaces = os.networkInterfaces()
  const result: string[] = []

  for (const name of Object.keys(interfaces)) {
    const lowerName = name.toLowerCase()
    if (lowerName.includes('vmware')
      || lowerName.includes('virtual')
      || lowerName.includes('vpn')
      || lowerName.includes('docker')
      || lowerName.includes('vethernet')) {
      continue
    }

    for (const iface of interfaces[name] || []) {
      if (iface.family === 'IPv4' && !iface.internal) {
        result.push(iface.address)
      }
    }
  }

  return result
}

3. 遍历 IP 请求验证

轮询所有 IP,尝试访问客户端服务,验证是否可用

private async testIPsParallel(ips: string[]): Promise<string | null> {
  if (ips.length === 0)
    return null
  return new Promise((resolve) => {
    const globalTimeout = setTimeout(() => {
      resolve(null)
    }, this.TIMEOUT * 1.5)

    const controllers = ips.map(() => new AbortController())
    let hasResolved = false
    let completedCount = 0

    const testIP = (ip: string, index: number) => {
      const controller = controllers[index]
      axios.get(`http://${ip}:${PORT}/api/task-server/ip`, {
        timeout: this.TIMEOUT,
        signal: controller.signal,
      })
        .then(() => {
          if (!hasResolved) {
            hasResolved = true
            clearTimeout(globalTimeout)
            controllers.forEach((c, i) => {
              if (i !== index)
                c.abort()
            })
            resolve(ip)
          }
        })
        .catch(() => {
          if (!hasResolved) {
            completedCount++
            if (completedCount >= ips.length) {
              clearTimeout(globalTimeout)
              resolve(null)
            }
          }
        })
    }
    ips.forEach(testIP)
  })
}

4. 添加缓存策略

对成功的 IP 进行缓存,设定缓存有效时间,避免重复请求

private cachedValidIP: string | null = null
private lastValidationTime = 0
private readonly CACHE_VALID_DURATION = 24 * 60 * 60 * 1000

三、完整代码

import os from 'node:os'
import axios from 'axios'
import { PORT } from '../../enum/env'

/**
 * IP管理器单例类
 * 用于获取并缓存本地有效IP地址
 */
export class IPManager {
  private static instance: IPManager
  private cachedValidIP: string | null = null
  private lastValidationTime = 0
  private readonly CACHE_VALID_DURATION = 24 * 60 * 60 * 1000
  private readonly TIMEOUT = 200
  private isTestingIPs = false

  private constructor() {}

  static getInstance(): IPManager {
    if (!IPManager.instance) {
      IPManager.instance = new IPManager()
    }
    return IPManager.instance
  }

  async getLocalIP(): Promise<string> {
    const now = Date.now()
    if (this.cachedValidIP && now - this.lastValidationTime < this.CACHE_VALID_DURATION) {
      console.log('从缓存中获取 IP', this.cachedValidIP)
      return this.cachedValidIP
    }

    if (this.isTestingIPs) {
      const allIPs = this.getAllPossibleIPs()
      return allIPs.length > 0 ? allIPs[0] : '127.0.0.1'
    }
    this.isTestingIPs = true

    try {
      const allIPs = this.getAllPossibleIPs()
      if (allIPs.length === 0) {
        return '127.0.0.1'
      }

      const validIP = await this.testIPsParallel(allIPs)
      if (validIP) {
        this.cachedValidIP = validIP
        this.lastValidationTime = now
        return validIP
      }
      return allIPs[0]
    }
    catch (error) {
      const allIPs = this.getAllPossibleIPs()
      return allIPs.length > 0 ? allIPs[0] : '127.0.0.1'
    }
    finally {
      this.isTestingIPs = false
    }
  }

  private getAllPossibleIPs(): string[] {
    const interfaces = os.networkInterfaces()
    const result: string[] = []

    for (const name of Object.keys(interfaces)) {
      const lowerName = name.toLowerCase()
      if (lowerName.includes('vmware')
        || lowerName.includes('virtual')
        || lowerName.includes('vpn')
        || lowerName.includes('docker')
        || lowerName.includes('vethernet')) {
        continue
      }

      for (const iface of interfaces[name] || []) {
        if (iface.family === 'IPv4' && !iface.internal) {
          result.push(iface.address)
        }
      }
    }

    return result
  }

  private async testIPsParallel(ips: string[]): Promise<string | null> {
    if (ips.length === 0)
      return null
    return new Promise((resolve) => {
      const globalTimeout = setTimeout(() => {
        resolve(null)
      }, this.TIMEOUT * 1.5)

      const controllers = ips.map(() => new AbortController())
      let hasResolved = false
      let completedCount = 0

      const testIP = (ip: string, index: number) => {
        const controller = controllers[index]
        axios.get(`http://${ip}:${PORT}/api/task-server/ip`, {
          timeout: this.TIMEOUT,
          signal: controller.signal,
          // validateStatus: status => status === 200,
        })
          .then(() => {
            if (!hasResolved) {
              hasResolved = true
              clearTimeout(globalTimeout)
              controllers.forEach((c, i) => {
                if (i !== index)
                  c.abort()
              })
              resolve(ip)
            }
          })
          .catch(() => {
            if (!hasResolved) {
              completedCount++
              if (completedCount >= ips.length) {
                clearTimeout(globalTimeout)
                resolve(null)
              }
            }
          })
      }
      ips.forEach(testIP)
    })
  }
}

/**
 * 获取本地有效IP地址
 */
export async function getLocalIP(): Promise<string> {
  return IPManager.getInstance().getLocalIP()
}

相关文章:

  • kotlin扩展函数的实现原理
  • 环境 tensorflow ERROR: No matching distribution found for ai-edge-litert
  • 【LeetCode基础算法】链表所有类型
  • 学透Spring Boot — 007. 加载配置
  • 【模拟CMOS集成电路笔记】轨到轨运放(Rail to Rail)基础(附带实例:基于1:3电流镜的轨到轨输入运放)
  • c++绘制爱心[特殊字符] 安装 EasyX 库
  • scala-stwitch分支结构
  • 【从0到1学Docker】Docker学习笔记
  • Java常用工具算法-1--哈希算法(MD5,SHA家族,SHA-256,BLAKE2)
  • 3万字长文详解Android AIDL 接口设计
  • 1.oracle修改配置文件
  • 区间预测 | MATLAB实现QRBiGRU门控循环单元分位数回归时间序列区间预测
  • 【SQL性能优化】预编译SQL:从注入防御到性能飞跃
  • 【复活吧,我的爱机!】Ideapad300-15isk拆机升级:加内存条 + 换固态硬盘 + 换电源
  • 腾讯位置服务学习记录
  • 汇编学习之《变址寄存器》
  • 下载安装mingw配置C++编译环境 及C环境
  • 深入理解 YUV 颜色空间:从原理到 Android 视频渲染
  • 【前端】创建一个vue3+JavaScript项目流程
  • 指纹浏览器技术解析:如何实现多账号安全运营与隐私保护
  • 如何做单位网站/今日国内最新新闻
  • 南宁疫情最新消息今天封城了/seo双标题软件
  • 合肥网站策划/做百度关键词排名的公司
  • 做网站需要多少固定带宽/品牌策划包括哪几个方面
  • 网站建设价格如何/南宁优化网站网络服务
  • 天天联盟没网站怎么做/百度竞价排名展示方式