HarmonyOS鸿蒙Next中怎样获取本机的IP地址

HarmonyOS鸿蒙Next中怎样获取本机的IP地址 怎样获取本机的IP地址?

3 回复

背景知识

解决方案

  • 场景一:设备连接Wi-Fi后,如何获取当前设备的IP地址?

    使用@ohos.wifiManager模块getIpInfo接口获取当前设备的IP地址。

    import { wifiManager } from '[@kit](/user/kit).ConnectivityKit';
    
    let ipAddress = wifiManager.getIpInfo().ipAddress;
    let ip = (ipAddress >>> 24) + '.' + (ipAddress >> 16 & 0xFF) + '.' + (ipAddress >> 8 & 0xFF) + '.' + (ipAddress & 0xFF);
    

    使用getLinkedInfo获取wifi网络链路信息

    wifiManager.getLinkedInfo().then(data => {
      console.info('get wifi linked info: ' + JSON.stringify(data));
    }).catch((error: number) => {
      console.error('get linked info error');
    });
    
  • 场景二:设备连接蜂窝网络后,如何获取当前设备的IP地址?

    使用@ohos.net.connection模块的getconnectionproperties接口获取ConnectionProperties信息,linkAddresses包含链路信息,dnses网络地址包含的IP地址。

    import { connection } from '[@kit](/user/kit).NetworkKit';
    import { BusinessError } from '[@kit](/user/kit).BasicServicesKit';
    
    [@Entry](/user/Entry)
    [@Component](/user/Component)
    struct Index {
      @State message: string = 'Hello World';
    
      build() {
        RelativeContainer() {
          Text(this.message)
            .id('HelloWorld')
            .fontSize($r('app.float.page_text_font_size'))
            .fontWeight(FontWeight.Bold)
            .alignRules({
              center: { anchor: '__container__', align: VerticalAlign.Center },
              middle: { anchor: '__container__', align: HorizontalAlign.Center }
            })
            .onClick(() => {
              this.message = 'Welcome';
              let netHandle: connection.NetHandle;
              let connectionproperties: connection.ConnectionProperties;
    
              connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
                if (netHandle.netId === 0) {
                  // 当前没有已连接的网络时,获取的netHandler的netid为0,属于异常场景,此处可以实际情况自行添加一些处理机制。
                  return;
                }
                netHandle = connection.getDefaultNetSync();
                connectionproperties = connection.getConnectionPropertiesSync(netHandle);
                console.info('Succeeded to get connectionproperties: ' + JSON.stringify(connectionproperties));
              });
            })
        }
        .height('100%')
        .width('100%')
      }
    }
    

更多关于HarmonyOS鸿蒙Next中怎样获取本机的IP地址的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,可通过@ohos.net.connection模块获取本机IP地址。使用connection.getDefaultNet()获取默认网络连接,再调用connection.getDefaultNet().getAddresses()获取网络地址列表。示例代码:先导入模块,然后获取网络句柄,最后遍历地址列表筛选IPv4或IPv6地址。需注意申请ohos.permission.GET_NETWORK_INFO网络权限。

在HarmonyOS Next中,可以通过NetworkManagerNetworkInterface类获取本机IP地址。以下是示例代码:

import network from '@ohos.net.network';

// 获取所有网络接口
let networkInterfaces = network.getNetworkInterfaces();

// 遍历网络接口获取IP地址
for (let i = 0; i < networkInterfaces.length; i++) {
  let ni = networkInterfaces[i];
  let addresses = ni.getAddresses();
  
  for (let j = 0; j < addresses.length; j++) {
    let address = addresses[j];
    // 过滤IPv4地址
    if (address.family === network.AF_INET) {
      console.log('Interface: ' + ni.getName());
      console.log('IP Address: ' + address.address);
    }
  }
}

注意:

  • 需要申请ohos.permission.INTERNET网络权限
  • 返回的地址列表包含IPv4和IPv6地址
  • 建议在主线程外执行网络操作
回到顶部