HarmonyOS 获取手机设备(非WIFI情况)在互联网环境下的公网IP的程序方法?

如何获取手机设备(非WIFI情况)在互联网环境下的公网IP的程序方法或者是可参考的文档地址?

阅读 599
1 个回答

使用接口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%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进