HarmonyOS 需要获取手机ip的方法

HarmonyOS
2024-12-23 16:36:44
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
put_get

参考如下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"
}
分享
微博
QQ
微信
回复
2024-12-23 20:16:55
相关问题
HarmonyOS 获取IP地址方法
416浏览 • 1回复 待解决
获取本地IP地址方法
2837浏览 • 1回复 待解决
有同步方法获取IP地址吗
763浏览 • 1回复 待解决
HarmonyOS 获取app网络ip
438浏览 • 1回复 待解决
需要一个获取当前省份方法
898浏览 • 1回复 待解决
HarmonyOS 如何获取设备ip地址
497浏览 • 1回复 待解决
HarmonyOS 如何获取网络IP地址
526浏览 • 1回复 待解决
HarmonyOS 如何获取设备ip
415浏览 • 1回复 待解决
HarmonyOS 获取本机ip地址
567浏览 • 1回复 待解决
HarmonyOS 如何获取蜂窝网IP地址
288浏览 • 1回复 待解决
HarmonyOS 如何获取当前设备 IP 地址
732浏览 • 1回复 待解决
HarmonyOS app获取本机ip地址
314浏览 • 1回复 待解决
如何获取蜂窝网络ip地址
780浏览 • 1回复 待解决
HarmonyOS 获取设备mac地址和ip地址
671浏览 • 1回复 待解决
如何获取当前设备所在网络ip
1104浏览 • 1回复 待解决
HarmonyOS 需要提供手机openssl库sdk
969浏览 • 1回复 待解决
HarmonyOS 如何获取ip地址和mac地址
641浏览 • 1回复 待解决
HarmonyOS 如何获取设备网络类型及ip
360浏览 • 1回复 待解决
nginx tcp转发 怎么获取IP
3127浏览 • 1回复 待解决
HarmonyOS 区分手机,pad方法
253浏览 • 1回复 待解决