HarmonyOS 需要获取手机ip的方法?

如题:HarmonyOS 需要获取手机ip的方法?

阅读 407
1 个回答

参考如下demo:

import connection from '@ohos.net.connection';
import hilog from '@ohos.hilog';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

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%')
  }
}

权限配置:

{
  'name': "ohos.permission.INTERNET"
},
{
  'name': "ohos.permission.GET_NETWORK_INFO"
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏