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

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

阅读 408
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
子站问答
访问
宣传栏