# ohos-ping **Repository Path**: Fie_Ryan/ohos-ping ## Basic Information - **Project Name**: ohos-ping - **Description**: 这是一个为鸿蒙(HarmonyOS)平台设计的网络 Ping 库,使用 TCP 连接测试来模拟 ICMP Ping 功能。由于鸿蒙系统对 ICMP 协议的限制,本库采用 TCP Socket 连接的方式来检测主机的可达性和响应时间。 - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: https://gitee.com/Fie_Ryan - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-03-06 - **Last Updated**: 2026-03-06 ## Categories & Tags **Categories**: Uncategorized **Tags**: ping ## README # Ping Library - 鸿蒙网络 Ping 库 ## 简介 这是一个为鸿蒙(HarmonyOS)平台设计的网络 Ping 库,使用 TCP 连接测试来模拟 ICMP Ping 功能。由于鸿蒙系统对 ICMP 协议的限制,本库采用 TCP Socket 连接的方式来检测主机的可达性和响应时间。 ## 功能特性 - ✅ TCP 连接模拟 Ping 功能 - ✅ 支持自定义端口配置 - ✅ 智能分层端口策略 - ✅ 单次 Ping 和连续 Ping 流 - ✅ 可配置超时和重试次数 - ✅ 网络状态检测工具 - ✅ IP 地址格式验证 ## 安装使用 ### 1. 添加依赖 在你的应用中使用 ohpm 下载安装: ```typescript ohpm install @ryan/tcp-ping ``` ### 2. 配置权限 在 `entry/src/main/module.json5` 中添加网络权限: ```json5 { "module": { "requestPermissions": [ { "name": "ohos.permission.INTERNET" }, { "name": "ohos.permission.GET_NETWORK_INFO" } ] } } ``` **权限说明:** - `ohos.permission.INTERNET` - 允许应用访问互联网(必需) - `ohos.permission.GET_NETWORK_INFO` - 允许获取网络状态信息(可选,用于 NetworkUtils) ### 3. 导入库 ```typescript import { PingManager, NetworkUtils } from '@ryan/tcp-ping'; ``` ### 4. 创建实例 ```typescript const pingManager = new PingManager(); ``` ## API 文档 ### PingManager 类 #### 方法列表 ##### `ping(host: string, timeout: number, count: number): Promise` 执行单次或多次 Ping 测试。 **参数:** - `host` - 目标主机地址(域名或 IP) - `timeout` - 超时时间(秒) - `count` - Ping 次数 **返回值:** `PingResult` 对象 **示例:** ```typescript const result = await pingManager.ping('www.baidu.com', 5, 3); console.log(`成功: ${result.success}, 响应时间: ${result.responseTime}ms`); ``` --- ##### `setCustomPorts(ports: number[]): void` 设置自定义端口列表。设置后,Ping 测试将只尝试连接这些端口。 **参数:** - `ports` - 端口号数组 **示例:** ```typescript // 只尝试 HTTP 和 HTTPS 端口 pingManager.setCustomPorts([80, 443]); // 尝试多个自定义端口 pingManager.setCustomPorts([80, 443, 8080, 8443, 3000]); ``` --- ##### `resetCustomPorts(): void` 重置为默认端口策略,清空自定义端口配置。 **示例:** ```typescript pingManager.resetCustomPorts(); ``` --- ##### `startPingStream(host: string, timeout: number, count: number, sink: EventSink): Promise` 启动持续的 Ping 流,适用于需要实时监控的场景。 **参数:** - `host` - 目标主机 - `timeout` - 超时时间(秒) - `count` - 总 Ping 次数 - `sink` - 事件接收器 --- ##### `stopPingStream(): void` 停止正在进行的 Ping 流。 **示例:** ```typescript pingManager.stopPingStream(); ``` --- ##### `dispose(): void` 释放资源,清理定时器。 **示例:** ```typescript pingManager.dispose(); ``` --- ### NetworkUtils 类 静态工具类,提供网络相关的辅助功能。 #### 方法列表 ##### `isNetworkAvailable(): Promise` 检查网络是否可用。 **返回值:** `true` 表示网络可用,`false` 表示不可用 **示例:** ```typescript const isAvailable = await NetworkUtils.isNetworkAvailable(); if (isAvailable) { console.log('网络已连接'); } ``` --- ##### `getNetworkType(): Promise` 获取当前网络类型。 **返回值:** `'wifi'` | `'cellular'` | `'unknown'` | `'none'` **示例:** ```typescript const networkType = await NetworkUtils.getNetworkType(); console.log(`当前网络类型: ${networkType}`); ``` --- ##### `isValidIP(ip: string): boolean` 验证 IPv4 地址格式是否正确。 **参数:** - `ip` - IP 地址字符串 **返回值:** `true` 表示格式正确,`false` 表示格式错误 **示例:** ```typescript const valid = NetworkUtils.isValidIP('192.168.1.1'); // true const invalid = NetworkUtils.isValidIP('256.1.1.1'); // false ``` --- ## 数据结构 ### PingResult 接口 ```typescript interface PingResult { host: string; // 目标主机 success: boolean; // 是否成功 responseTime?: number; // 响应时间(毫秒) ttl?: number; // TTL 值 error?: string; // 错误信息 sequence?: number; // 序列号 } ``` ## 端口策略 ### 默认分层策略 当未设置自定义端口时,库会按以下优先级尝试连接: **第一层(Primary)- 最常用端口:** - 80 (HTTP) - 443 (HTTPS) - 8080 (HTTP 备用) **第二层(Secondary)- 常用服务端口:** - 22 (SSH) - 3389 (RDP) - 8443 (HTTPS 备用) - 8000 (开发服务器) - 3000 (Node.js) - 5000 (Flask) - 8888 (Jupyter) **第三层(Tertiary)- 其他端口:** - 23 (Telnet) - 21 (FTP) - 25 (SMTP) - 53 (DNS) - 3306 (MySQL) - 5432 (PostgreSQL) - 6379 (Redis) - 5900 (VNC) - 4200 (Angular) - 27017 (MongoDB) ### 自定义端口策略 使用 `setCustomPorts()` 后,将跳过默认分层策略,只尝试指定的端口。 ## 使用场景 ### 场景 1:基本 Ping 测试 ```typescript import { PingManager } from 'library'; const pingManager = new PingManager(); // Ping 百度 3 次,超时 5 秒 const result = await pingManager.ping('www.baidu.com', 5, 3); if (result.success) { console.log(`Ping 成功!响应时间: ${result.responseTime}ms`); } else { console.log(`Ping 失败: ${result.error}`); } ``` ### 场景 2:自定义端口测试 ```typescript import { PingManager } from 'library'; const pingManager = new PingManager(); // 只测试 Web 服务端口 pingManager.setCustomPorts([80, 443, 8080]); const result = await pingManager.ping('example.com', 3, 1); console.log(result); // 恢复默认策略 pingManager.resetCustomPorts(); ``` ### 场景 3:网络检测 + Ping ```typescript import { PingManager, NetworkUtils } from 'library'; // 先检查网络状态 const isAvailable = await NetworkUtils.isNetworkAvailable(); if (!isAvailable) { console.log('网络不可用'); return; } // 获取网络类型 const networkType = await NetworkUtils.getNetworkType(); console.log(`当前网络: ${networkType}`); // 执行 Ping const pingManager = new PingManager(); const result = await pingManager.ping('www.google.com', 5, 3); console.log(result); ``` ### 场景 4:批量主机测试 ```typescript import { PingManager } from 'library'; const pingManager = new PingManager(); const hosts = ['www.baidu.com', 'www.taobao.com', 'www.jd.com']; for (const host of hosts) { const result = await pingManager.ping(host, 3, 1); console.log(`${host}: ${result.success ? '可达' : '不可达'} (${result.responseTime}ms)`); } ``` ### 场景 5:特定服务端口测试 ```typescript import { PingManager } from 'library'; const pingManager = new PingManager(); // 测试数据库服务器 pingManager.setCustomPorts([3306, 5432, 6379]); // MySQL, PostgreSQL, Redis const dbResult = await pingManager.ping('db.example.com', 3, 1); // 测试 Web 服务器 pingManager.setCustomPorts([80, 443]); const webResult = await pingManager.ping('web.example.com', 3, 1); // 测试 SSH 服务器 pingManager.setCustomPorts([22]); const sshResult = await pingManager.ping('ssh.example.com', 3, 1); ``` ## 注意事项 1. **权限配置**:使用前必须在 module.json5 中配置 `ohos.permission.INTERNET` 权限 2. **ICMP 限制**:由于鸿蒙系统限制,本库使用 TCP 连接代替 ICMP Ping 3. **端口依赖**:Ping 成功依赖于目标主机至少有一个端口开放 4. **防火墙影响**:防火墙可能阻止 TCP 连接,导致 Ping 失败 5. **响应时间**:TCP 连接时间可能略高于真实的 ICMP Ping 时间 6. **资源释放**:使用完毕后建议调用 `dispose()` 释放资源 ## 技术实现 - 使用 `@ohos.net.socket` 进行 TCP 连接 - 使用 `@ohos.net.connection` 检测网络状态 - 使用 `@ohos.hilog` 记录日志 - 采用 Promise 和 async/await 异步编程模式