Network Connection Management (C/C++)
When to Use
The NetConnection module provides the capability of querying common network information.
Available APIs
The following table lists the common NetConnection APIs. For details, see net_connection.h.
| API | Test Description |
|---|---|
| OH_NetConn_HasDefaultNet(int32_t *hasDefaultNet) | Checks whether the default data network is activated and determines whether a network connection is available. |
| OH_NetConn_GetDefaultNet(NetConn_NetHandle *netHandle) | Obtains the default active data network. |
| OH_NetConn_IsDefaultNetMetered(int32_t *isMetered) | Checks whether the data traffic usage on the current network is metered. |
| OH_NetConn_GetConnectionProperties(NetConn_NetHandle *netHandle, NetConn_ConnectionProperties *prop) | Obtains network connection information based on the specified netHandle. |
| OH_NetConn_GetNetCapabilities (NetConn_NetHandle *netHandle, NetConn_NetCapabilities *netCapacities) | Obtains network capability information based on the specified netHandle. |
| OH_NetConn_GetDefaultHttpProxy (NetConn_HttpProxy *httpProxy) | Obtains the default HTTP proxy configuration of the network. If the global proxy is set, the global HTTP proxy configuration is returned. If the application has been bound to the network specified by netHandle, the HTTP proxy configuration of this network is returned. In other cases, the HTTP proxy configuration of the default network is returned. |
| OH_NetConn_GetAddrInfo (char *host, char *serv, struct addrinfo *hint, struct addrinfo **res, int32_t netId) | Obtains the DNS result based on the specified netId. |
| OH_NetConn_FreeDnsResult(struct addrinfo *res) | Releases the DNS query result. |
| OH_NetConn_GetAllNets(NetConn_NetHandleList *netHandleList) | Obtains the list of all connected networks. |
| OHOS_NetConn_RegisterDnsResolver(OH_NetConn_CustomDnsResolver resolver) | Registers a custom DNS resolver. Note: This API is deprecated since API version 13. You are advised to use OH_NetConn_RegisterDnsResolver instead. |
| OHOS_NetConn_UnregisterDnsResolver(void) | Unregisters a custom DNS resolver. Note: This API is deprecated since API version 13. You are advised to use OH_NetConn_UnregisterDnsResolver instead. |
| OH_NetConn_RegisterDnsResolver(OH_NetConn_CustomDnsResolver resolver) | Registers a custom DNS resolver. |
| OH_NetConn_UnregisterDnsResolver(void) | Unregisters a custom DNS resolver. |
| OH_NetConn_SetPacUrl(const char *pacUrl) | Sets the URL of the system-level proxy auto-config (PAC) script. |
| OH_NetConn_GetPacUrl(char *pacUrl) | Obtains the URL of the system-level PAC script. |
| OH_NetConn_QueryProbeResult(char *destination, int32_t duration, NetConn_ProbeResultInfo *probeResultInfo) | Queries the probe result. |
| OH_NetConn_QueryTraceRoute(char *destination, NetConn_TraceRouteOption *option, NetConn_TraceRouteInfo *traceRouteInfo) | Queries trace route information. |
Development Example
How to Develop
To use related APIs to obtain network information, you need to create a Native C++ project, encapsulate the APIs in the source file, and call these APIs at the ArkTS layer. You can use hilog or console.log to print the log information on the console or generate device logs.
This document describes how to obtain the default active data network as an example.
For details about other APIs, see the Complete Sample Code.
Adding Dependencies
Adding the Dynamic Link Library
Add the following library to CMakeLists.txt.
libace_napi.z.so
libnet_connection.so
Including Header Files
#include "napi/native_api.h"
#include "network/netmanager/net_connection.h"
#include "network/netmanager/net_connection_type.h"
Building the Project
-
Write the code for calling the API in the source file, encapsulate it into a value of the
napi_valuetype, and return the value to the Node.js environment.> **NOTE**// Obtain the default network. static napi_value GetDefaultNet(napi_env env, napi_callback_info info) { size_t argc = 1; // Expect one function. napi_value args[1] = {nullptr}; // Store the received parameters. napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); // ... int32_t param; napi_get_value_int32(env, args[0], ¶m); // Obtain an integer from args[0] and store the integer in param. NetConn_NetHandle netHandle; if (param == 0) { // If the parameter is 0 param = OH_NetConn_GetDefaultNet(NULL); } else { param = OH_NetConn_GetDefaultNet(&netHandle); } napi_value result; napi_create_int32(env, param, &result); return result; } // Obtain the default network ID. static napi_value NetId(napi_env env, napi_callback_info info) { int32_t defaultNetId; NetConn_NetHandle netHandle; OH_NetConn_GetDefaultNet(&netHandle); defaultNetId = netHandle.netId; // Obtain the default netId. napi_value result; napi_create_int32(env, defaultNetId, &result); return result; }
The two functions are used to obtain information about the default network connection of the system. Wherein, GetDefaultNet is used to receive the test parameters passed from ArkTS and return the corresponding return value after the API is called. You can change param as needed. If the return value is **0**, the parameters are obtained successfully. If the return value is **401**, the parameters are incorrect. If the return value is **201**, the user does not have the operation permission. NetId indicates the ID of the default network connection. You can use the information for further network operations. -
Initialize and export the
napi_valueobjects encapsulated through NAPI, and expose the preceding two functions to JavaScript through external function APIs.EXTERN_C_START static napi_value Init(napi_env env, napi_value exports) { // Information used to describe an exported attribute. Two properties are defined here: `GetDefaultNet` and `NetId`. napi_property_descriptor desc[] = { {"GetDefaultNet", nullptr, GetDefaultNet, nullptr, nullptr, nullptr, napi_default, nullptr}, {"NetId", nullptr, NetId, nullptr, nullptr, nullptr, napi_default, nullptr}, // ... }; napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); return exports; } EXTERN_C_END -
Register the objects successfully initialized in the previous step into the
Node.jsfile by using thenapi_module_registerfunction ofRegisterEntryModule.static napi_module demoModule = { .nm_version = 1, .nm_flags = 0, .nm_filename = nullptr, .nm_register_func = Init, .nm_modname = "entry", .nm_priv = ((void *)0), .reserved = {0}, }; extern "C" __attribute__((constructor)) void RegisterEntryModule(void) { napi_module_register(&demoModule); } -
Define the types of the two functions in the
index.d.tsfile of the project.- The
GetDefaultNetfunction accepts the numeric parameter code and returns a numeric value. - The
NetIdfunction does not accept parameters and returns a numeric value.
export const GetDefaultNet: (code: number) => number; export const NetId: () => number; - The
-
Call the encapsulated APIs in the
index.etsfile.import testNetManager from 'libentry.so'; import { hilog } from '@kit.PerformanceAnalysisKit'; enum ReturnCode { SUCCESS = 0, // Operation succeeded. MISSING_PERMISSION = 201, // Missing permissions. PARAMETER_ERROR = 401, // Parameter error. } // ... @Entry @Component struct Index { @State message: string = ''; // Display log messages. // ... build() { Column() { // Display logs output by Logger. // ... Text(this.message) .fontSize(16) .fontColor(Color.Black) .margin({ bottom: 10 }) .id('test-message') // Set an ID for the test message to facilitate content obtaining. Button($r('app.string.GetDefaultNet')) .onClick(() => { this.GetDefaultNet(); }) // ... Button($r('app.string.CodeNumber')) .onClick(() => { this.CodeNumber(); }) // ... }.width('100%').height('100%').justifyContent(FlexAlign.Center); } GetDefaultNet() { let netId = testNetManager.NetId(); // ... hilog.info(0x0000, 'testTag', 'The defaultNetId is [' + netId + ']'); // ... } CodeNumber() { let testParam = 1; // ... let codeNumber = testNetManager.GetDefaultNet(testParam); switch (codeNumber) { case ReturnCode.SUCCESS: hilog.info(0x0000, 'testTag', 'Test success. [' + codeNumber + ']'); // ... break; case ReturnCode.MISSING_PERMISSION: hilog.info(0x0000, 'testTag', 'Missing permissions. [' + codeNumber + ']'); // ... break; case ReturnCode.PARAMETER_ERROR: hilog.info(0x0000, 'testTag', 'Parameter error. [' + codeNumber + ']'); // ... break; default: hilog.info(0x0000, 'testTag', 'Unexpected result: [' + codeNumber + ']'); // ... break; } // ... } // ... } -
Configure the
CMakeLists.txtfile. Add the required shared library, that is,libnet_connection.so, totarget_link_librariesin theCMakeLists.txtfile automatically generated by the project.NOTE
As shown in the following figure,
entryinadd_libraryis themodnameautomatically generated by the project. If you want to change its value, ensure that it is the same as the.nm_modnamein step 3.
After the preceding steps, the entire project is set up. Then, you can connect to the device to run the project to view logs.
Test Procedure
-
Connect the device and use DevEco Studio to open the project.
-
Run the project. The following figure is displayed on the device.
- If you click
GetDefaultNet, you'll obtain the default network ID. - If you click
codeNumber, you'll obtain the status code returned by the API.

- If you click
-
Click
GetDefaultNet. The following log is displayed, as shown below:
-
Click
codeNumber. The status code is displayed, as shown below:
Samples
For details about network connection development, see Network Connection Development.