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()
}
Electron 开发:获取当前客户端 IP的更多相关文章
- ABP vNext 审计日志获取真实客户端IP
背景 在使用ABP vNext时,当需要记录审计日志时,我们按照https://docs.abp.io/zh-Hans/abp/latest/Audit-Logging配置即可开箱即用,然而在实际生产 ...
- nginx+tomcat集群配置(3)---获取真实客户端IP
前言: 在初步构建的nginx+tomcat服务集群时, 发现webserver获取到的客户端ip都是同一个, 皆为作为反向代理服务的nginx所在的机器IP. 这不太符合我们的基本需求, 为将来的数 ...
- nginx做反向负载均衡,后端服务器获取真实客户端ip(转)
首先,在前端nginx上需要做如下配置: location / proxy_set_hearder host $host; proxy_set_header X-forw ...
- 根据Request获取真实客户端IP
转载:http://www.cnblogs.com/icerainsoft/p/3584532.html 在JSP里,获取客户端的IP地址的方法是:request.getRemoteAddr() ,这 ...
- tornado 反向代理后 获取真实客户端IP
首先,nginx必定会设置一个Header传送过来真实的IP nginx.conf server { proxy_set_header X-Real-IP $remote_addr; location ...
- nginx 部署 .net core 获取的客户端ip为127.0.0.1
采用nginx和.net core 部署一套api接口到服务器上,发现获取到的ip地址为127.0.0.1 经过检查发现,需要在nginx配置上以下参数 proxy_set_header Host $ ...
- nginx设置反向代理,获取真实客户端ip
upstream这个模块提供一个简单方法来实现在轮询和客户端IP之间的后端服务器负荷平衡. upstream abc.com { server 127.0.0.1:8080; server 127.0 ...
- Vue实战041:获取当前客户端IP地址详解(内网和外网)
前言 我们经常会有需求,希望能获取的到当前用户的IP地址,而IP又分为公网ip(也称外网)和私网IP(也称内网IP),IP地址是IP协议提供的一种统一的地址格式,每台设备都设定了一个唯一的IP地址”, ...
- gin框架中设置信任代理IP并获取远程客户端IP
package main import ( "fmt" "github.com/gin-gonic/gin" ) func main() { gin.SetMo ...
- 使用electron开发指静脉客户端遇到的问题总结
使用electron 使用nodejs 的ffi模块调用dll文件 总结1.electron 与nodejs版本不需要一致,甚至nodejs版本应该高于electron的node版本2.要安装 Vis ...
随机推荐
- 九. Redis 持久化-RDB(详细讲解说明,一个配置一个说明分析,步步讲解到位)
九. Redis 持久化-RDB(详细讲解说明,一个配置一个说明分析,步步讲解到位) @ 目录 九. Redis 持久化-RDB(详细讲解说明,一个配置一个说明分析,步步讲解到位) 1. RDB 概述 ...
- Vmware共享文件夹安装设置方法(window与Linux使用共享文件夹)
Vmware共享文件夹安装设置方法 注意:如果按照了工具,设置了共享文件夹,Linux下面还是没有的话,可以运行下面的命令,就会加载共享文件夹了 vmhgfs-fuse .host:/ /mnt/hg ...
- RocketMQ实战—8.营销系统业务和方案介绍
大纲 1.电商核心交易场景的业务流程 2.电商支付后履约场景的业务流程 3.电商营销场景的业务说明 4.电商促销活动的Push推送 5.会员与推送的数据库表结构 6.营销系统的数据库表结构 7.营销系 ...
- Maven配置多数据源
一.配置文件 修改maven配置文件,用户目录下.m2文件夹中的setting.xml,内容如下 <?xml version="1.0" encoding="UTF ...
- KUKA库卡机器人维修
KUKA库卡机器人作为生产线上的核心设备,一旦出现KUKA机械手故障,将直接影响整个生产线的运行效率.及时的库卡机器人维修工作不仅能够迅速恢复机器人的工作状态,减少生产停滞时间,还能通过预防性维护降低 ...
- 软件工程: SDLC V模型
V型 V-model 代表一个开发过程,可以被认为是瀑布模型的扩展,是更通用的 V-model 的一个例子.不是以线性方式向下移动,而是在编码阶段之后向上弯曲工艺步骤,以形成典型的 V 形.V 模型展 ...
- Halcon2DMeasure常用算子
1.create_metrology_model() create_metrology_model( : : : MetrologyHandle) 函数说明: 创建测量几何图形所需的数据结构/模型 ...
- C# 将list进行随机排序
private List<T> RandomSortList<T>(List<T> ListT) { Random random = new Random(); L ...
- C#枚举帮助EnumHelper
1 public class EnumHelper 2 { 3 #region 获取枚举 4 public static List<EnumValue> GetEnumList(Type ...
- excel怎么根据数值做进度条
开始->条件格式->数据条