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

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

一、背景与需求

1. 项目背景

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

2. 初始方案与问题

2.1. 初始方案:通过代码获取本机 IP

typescript 复制代码
/**
 * 获取局域网 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

typescript 复制代码
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,尝试访问客户端服务,验证是否可用

typescript 复制代码
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 进行缓存,设定缓存有效时间,避免重复请求

typescript 复制代码
private cachedValidIP: string | null = null
private lastValidationTime = 0
private readonly CACHE_VALID_DURATION = 24 * 60 * 60 * 1000

三、完整代码

typescript 复制代码
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()
}
相关推荐
方也_arkling9 分钟前
别名路径联想提示。@/统一文件路径的配置
前端·javascript
毕设源码-朱学姐11 分钟前
【开题答辩全过程】以 基于web教师继续教育系统的设计与实现为例,包含答辩的问题和答案
前端
qq_1777673716 分钟前
React Native鸿蒙跨平台剧集管理应用实现,包含主应用组件、剧集列表、分类筛选、搜索排序等功能模块
javascript·react native·react.js·交互·harmonyos
qq_1777673722 分钟前
React Native鸿蒙跨平台自定义复选框组件,通过样式数组实现选中/未选中状态的样式切换,使用链式调用替代样式数组,实现状态驱动的样式变化
javascript·react native·react.js·架构·ecmascript·harmonyos·媒体
web打印社区25 分钟前
web-print-pdf:突破浏览器限制,实现专业级Web静默打印
前端·javascript·vue.js·electron·html
RFCEO1 小时前
前端编程 课程十三、:CSS核心基础1:CSS选择器
前端·css·css基础选择器详细教程·css类选择器使用方法·css类选择器命名规范·css后代选择器·精准选中嵌套元素
烬头88211 小时前
React Native鸿蒙跨平台采用了函数式组件的形式,通过 props 接收分类数据,使用 TouchableOpacity实现了点击交互效果
javascript·react native·react.js·ecmascript·交互·harmonyos
Amumu121381 小时前
Vuex介绍
前端·javascript·vue.js
We་ct1 小时前
LeetCode 54. 螺旋矩阵:两种解法吃透顺时针遍历逻辑
前端·算法·leetcode·矩阵·typescript
2601_949809591 小时前
flutter_for_openharmony家庭相册app实战+相册详情实现
javascript·flutter·ajax