HarmonyOS鸿蒙Next中如何获取网络的连接信息

HarmonyOS鸿蒙Next中如何获取网络的连接信息

如何获取网络的连接信息

坚果,润开鸿技术专家,InfoQ签约作者,OpenHarmony布道师,多个平台的专家博主。
主页:https://gitee.com/jianguo888/

1.导入模块

//网络连接管理模块
import connection from '@ohos.net.connection'

2.connection.getConnectionProperties

function getConnectionProperties(netHandle: NetHandle): Promise<ConnectionProperties>;

获取netHandle对应的网络的连接信息,使用Promise方式作为异步方法。

需要权限

module.json中配置

"requestPermissions": [
  {
    "name": "ohos.permission.GET_NETWORK_INFO"
  }
],

代码

connection.getDefaultNet().then(function (netHandle) {
 connection.getConnectionProperties(netHandle).then(function (info) {
   console.info(JSON.stringify(info))
 })
})

控制台输出

{
  "interfaceName": "wlan0",
  "domains": "",
  "mtu": 0,
  "linkAddresses": [
    {
      "address": {
        "address": "192.168.43.91",
        "family": 0,
        "port": 0
      },
      "prefixLength": 24
    }
  ],
  "routes": [
    {
      "interface": "wlan0",
      "destination": {
        "address": "0.0.0.0",
        "prefixLength": 0
      },
      "gateway": {
        "address": "192.168.43.1",
        "prefixLength": 0
      },
      "hasGateway": true,
      "isDefaultRoute": false
    },
    {
      "interface": "wlan0",
      "destination": {
        "address": "192.168.43.0",
        "prefixLength": 24
      },
      "gateway": {
        "address": "0.0.0.0",
        "prefixLength": 0
      },
      "hasGateway": true,
      "isDefaultRoute": false
    }
  ],
  "dnses": [
    {
      "address": "192.168.43.1",
      "family": 0,
      "port": 0
    },
    {
      "address": "8.8.8.8",
      "family": 0,
      "port": 0
    }
  ]
}

参数说明

ConnectionProperties

网络连接信息。

  • interfaceName:网卡名称。
  • domains:所属域,默认""。
  • linkAddresses:链路信息。[LinkAddress类型]
  • routes:路由信息。
  • dnses:网络地址,
  • mtu最大传输单元。

LinkAddress

网络链路信息。

  • address:链路地址。[NetAddress]
  • prefixLength:链路地址前缀的长度。

RouteInfo

网络路由信息。

  • interface:网卡名称。
  • destination:目的地址。[LinkAddress]
  • gateway:网关地址。[NetAddress]
  • hasGateway: 是否有网关。
  • isDefaultRoute:是否为默认路由。

NetAddress

网络地址。

  • address: 地址。
  • family:IPv4 = 1,IPv6 = 2,默认IPv4。
  • port:端口,取值范围[0, 65535]。

更多关于HarmonyOS鸿蒙Next中如何获取网络的连接信息的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next中如何获取网络的连接信息的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,可以通过@ohos.net.connection模块获取网络连接信息。首先,使用getDefaultNet方法获取默认网络,然后通过getNetCapabilitiesgetNetProperties方法分别获取网络能力和属性信息。

示例代码如下:

import connection from '@ohos.net.connection';

let netHandle = connection.getDefaultNet();
let capabilities = netHandle.getNetCapabilities();
let properties = netHandle.getNetProperties();

console.log("Network Capabilities:", capabilities);
console.log("Network Properties:", properties);

通过这些方法,可以获取网络类型、信号强度、IP地址等详细信息。

回到顶部