DEV Community

HarmonyOS
HarmonyOS

Posted on

How to obtain the local machine's IP address

Read the original article:How to obtain the local machine's IP address

How to obtain the local machine's IP address

Requirement Description

How to obtain the local device’s IP address when connected to Wi-Fi or cellular networks.

Background Knowledge

· @ohos.wifiManager (WLAN) module mainly provides basic WLAN functions (wireless access, encryption, roaming, etc.), peer-to-peer services, and WLAN message notifications, enabling applications to connect and communicate with other devices via WLAN.

· @ohos.net.connection module provides basic capabilities for network management, including obtaining the default active data network, retrieving all active data networks, enabling/disabling airplane mode, and fetching network capability information.

· connection.getConnectionPropertiesSync retrieves the connection information for a given netHandle. The returned ConnectionProperties object contains linkAddresses, which include the address (IP information).

Implementation Steps

Scenario 1: Device connected to Wi-Fi

  1. Use the wifiManager.getIpInfo() interface to obtain the current device IP address.

  2. Optionally, use getLinkedInfo() to fetch additional Wi-Fi network link information.

Scenario 2: Device connected to Cellular Network

  1. Use the @ohos.net.connection module’s getConnectionProperties() interface to get ConnectionProperties.

  2. The linkAddresses field contains link address information, and dnses includes IP address information.

  3. Ensure permission ohos.permission.GET_NETWORK_INFO is granted.

Code Snippet / Configuration

Wi-Fi connection example:

import { wifiManager } from '@kit.ConnectivityKit'; 

let ipAddress = wifiManager.getIpInfo().ipAddress; 
let ip = (ipAddress >>> 24) + "." + (ipAddress >> 16 & 0xFF) + "." + (ipAddress >> 8 & 0xFF) + "." + (ipAddress & 0xFF);

wifiManager.getLinkedInfo().then(data => {
  console.info("get wifi linked info: " + JSON.stringify(data));
}).catch((error:number) => {
  console.error("get linked info error");
});
Enter fullscreen mode Exit fullscreen mode

Cellular connection example:

import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@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) {
              // When there is no currently connected network, the netid obtained from the netHandler is 0, which is an abnormal scenario. In this case, you can add some handling mechanisms based on the actual situation.
              return;
            }
            netHandle = connection.getDefaultNetSync();
            connectionproperties = connection.getConnectionPropertiesSync(netHandle);
            console.info('Succeeded to get connectionproperties: ' + JSON.stringify(connectionproperties));
          });
        })
    }
    .height('100%')
    .width('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

Test Results

· Successfully retrieves the current device IP when connected to Wi-Fi using getIpInfo.

· Successfully retrieves the IP information when connected to a cellular network via getConnectionProperties.

· Requires ohos.permission.GET_NETWORK_INFO permission.

Limitations or Considerations

· Supported from API Version 19 Release and above.

· Requires HarmonyOS 5.1.1 Release SDK or later.

· Must be compiled and run using DevEco Studio 5.1.1 Release or later.

Related Documents or Links

· HarmonyOS Network Documentation

Written by Baris Tuzemen

Top comments (0)