使用接口connection.getConnectionProperties可获取当前使用网络IP,模块需配置权限:ohos.permission.GET\_NETWORK\_INFO,参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-net-connection-V5\#connectiongetconnectionproperties参考以下demo:import connection from '@ohos.net.connection'; import hilog from '@ohos.hilog'; import { common } from '@kit.AbilityKit'; const TAG: string = 'testTag' /** * 获取设备ip */ async function getLocalIp() { try { hilog.info(0x00000, TAG, '判断是否存在激活的网络连接'); let hasNet = connection.hasDefaultNetSync() if (hasNet) { hilog.info(0x00000, TAG, '存在默认激活的网络'); } else { hilog.error(0x00000, TAG, '不存在激活的网络'); return } let handleResult = await connection.getDefaultNet() if (handleResult) { let connectionProperties = await connection.getConnectionProperties(handleResult) if (connectionProperties && connectionProperties.linkAddresses) { connectionProperties.linkAddresses.forEach((address: connection.LinkAddress, index: number) => { hilog.info(0x00000, TAG, '索引:' + index + ',值:' + JSON.stringify(address)); }) } } } catch (e) { hilog.error(0x00000, TAG, `获取网络信息出现异常,异常信息 %{public}s`, JSON.stringify(e) ?? ''); } } @Entry @Component struct getLocalIpTest { @State message: string = 'Hello World'; context = getContext(this) as common.UIAbilityContext; build() { RelativeContainer() { Text(this.message) .id('HelloWorld') .fontSize(50) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: '__container__', align: VerticalAlign.Center }, middle: { anchor: '__container__', align: HorizontalAlign.Center } }) .onClick(() => { getLocalIp() }) }.height('100%').width('100%') } }
使用接口connection.getConnectionProperties可获取当前使用网络IP,模块需配置权限:ohos.permission.GET\_NETWORK\_INFO,参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-net-connection-V5\#connectiongetconnectionproperties
参考以下demo: