1# Network Connection Development 2 3## When to Use 4 5The **NetConnection** module provides the capability of querying common network information. 6 7## Available APIs 8 9The following table lists the common **NetConnection** APIs. For details, see [NetConnection](../reference/apis-network-kit/_net_connection.md). 10 11 12| API| **Test Description**| 13| -------- | -------- | 14| OH_NetConn_HasDefaultNet(int32_t \*hasDefaultNet) | Checks whether the default data network is activated and determines whether a network connection is available.| 15| OH_NetConn_GetDefaultNet(NetConn_NetHandle \*netHandle) | Obtains the default active data network.| 16| OH_NetConn_IsDefaultNetMetered(int32_t \*isMetered) | Checks whether the data traffic usage on the current network is metered.| 17| OH_NetConn_GetConnectionProperties(NetConn_NetHandle \*netHandle, NetConn_ConnectionProperties *prop) | Obtains network connection information based on the specified **netHandle**.| 18| OH_NetConn_GetNetCapabilities (NetConn_NetHandle \*netHandle, NetConn_NetCapabilities \*netCapacities) | Obtains network capability information based on the specified **netHandle**.| 19| 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.| 20| 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**.| 21| OH_NetConn_FreeDnsResult(struct addrinfo \*res) | Releases the DNS query result.| 22| OH_NetConn_GetAllNets(NetConn_NetHandleList \*netHandleList) | Obtains the list of all connected networks.| 23| OHOS_NetConn_RegisterDnsResolver(OH_NetConn_CustomDnsResolver resolver) | Registers a custom DNS resolver.<br>Note: This API is deprecated since API version 13.<br>You are advised to use **OH_NetConn_RegisterDnsResolver** instead.| 24| OHOS_NetConn_UnregisterDnsResolver(void) | Unregisters a custom DNS resolver.<br>Note: This API is deprecated since API version 13.<br>You are advised to use **OH_NetConn_UnregisterDnsResolver** instead.| 25| OH_NetConn_RegisterDnsResolver(OH_NetConn_CustomDnsResolver resolver) | Registers a custom DNS resolver.| 26| OH_NetConn_UnregisterDnsResolver(void) | Unregisters a custom DNS resolver.| 27 28## Development Example 29 30### How to Develop 31 32To 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. 33 34This document describes how to obtain the default active data network as an example. 35 36### Adding Dependencies 37 38**Adding the Dynamic Link Library** 39 40Add the following library to **CMakeLists.txt**. 41 42```txt 43libace_napi.z.so 44libnet_connection.so 45``` 46 47**Including Header Files** 48 49```c 50#include "napi/native_api.h" 51#include "network/netmanager/net_connection.h" 52#include "network/netmanager/net_connection_type.h" 53``` 54 55### Building the Project 56 571. Write the code for calling the API in the source file, encapsulate it into a value of the `napi_value` type, and return the value to the Node.js environment. 58 59```C 60// Get the execution results of the default network connection. 61static napi_value GetDefaultNet(napi_env env, napi_callback_info info) 62{ 63 size_t argc = 1; 64 napi_value args[1] = {nullptr}; 65 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 66 int32_t param; 67 napi_get_value_int32(env, args[0], ¶m); 68 69 NetConn_NetHandle netHandle; 70 if (param== 0) { 71 param= OH_NetConn_GetDefaultNet(NULL); 72 } else { 73 param= OH_NetConn_GetDefaultNet(&netHandle); 74 } 75 76 napi_value result; 77 napi_create_int32(env, param, &result); 78 return result; 79} 80 81// Get the ID of the default network connection. 82static napi_value NetId(napi_env env, napi_callback_info info) { 83 int32_t defaultNetId; 84 85 NetConn_NetHandle netHandle; 86 OH_NetConn_GetDefaultNet(&netHandle); 87 defaultNetId = netHandle.netId; // Get the default netId 88 89 napi_value result; 90 napi_create_int32(env, defaultNetId, &result); 91 92 return result; 93} 94``` 95 96> **NOTE**<br>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. 97 98 992. Initialize and export the `napi_value` objects encapsulated through **NAPI**, and expose the preceding two functions to JavaScript through external function APIs. 100 101```C 102EXTERN_C_START 103static napi_value Init(napi_env env, napi_value exports) 104{ 105 // Information used to describe an exported attribute. Two properties are defined here: `GetDefaultNet` and `NetId`. 106 napi_property_descriptor desc[] = { 107 {"GetDefaultNet", nullptr, GetDefaultNet, nullptr, nullptr, nullptr, napi_default, nullptr}, 108 {"NetId", nullptr, NetId, nullptr, nullptr, nullptr, napi_default, nullptr}}; 109 napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); 110 return exports; 111} 112EXTERN_C_END 113``` 114 1153. Register the objects successfully initialized in the previous step into the Node.js file by using the `napi_module_register` function of `RegisterEntryModule`. 116 117```C 118static napi_module demoModule = { 119 .nm_version = 1, 120 .nm_flags = 0, 121 .nm_filename = nullptr, 122 .nm_register_func = Init, 123 .nm_modname = "entry", 124 .nm_priv = ((void*)0), 125 .reserved = { 0 }, 126}; 127 128extern "C" __attribute__((constructor)) void RegisterEntryModule(void) 129{ 130 napi_module_register(&demoModule); 131} 132``` 133 1344. Define the types of the two functions in the `index.d.ts ` file of the project. 135 136- The `GetDefaultNet ` function accepts the numeric parameter code and returns a numeric value. 137- The `NetId` function does not accept parameters and returns a numeric value. 138 139```ts 140export const GetDefaultNet: (code: number) => number; 141export const NetId: () => number; 142``` 143 1445. Call the encapsulated APIs in the `index.ets` file. 145 146```ts 147import testNetManager from 'libentry.so'; 148 149@Entry 150@Component 151struct Index { 152 @State message: string = ''; 153 154 build() { 155 Row() { 156 Column() { 157 Text(this.message) 158 .fontSize(50) 159 .fontWeight(FontWeight.Bold) 160 Button('GetDefaultNet').onClick(event => { 161 this.GetDefaultNet(); 162 }) 163 Button('CodeNumber').onClick(event =>{ 164 this.CodeNumber(); 165 }) 166 } 167 .width('100%') 168 } 169 .height('100%') 170 } 171 172 GetDefaultNet() { 173 let netid = testNetManager.NetId(); 174 console.log("The defaultNetId is [" + netid + "]"); 175 } 176 177 CodeNumber() { 178 let testParam = 0; 179 let codeNumber = testNetManager.GetDefaultNet(testParam); 180 if (codeNumber === 0) { 181 console.log("Test success. [" + codeNumber + "]"); 182 } else if (codeNumber === 201) { 183 console.log("Missing permissions. [" + codeNumber + "]"); 184 } else if (codeNumber === 401) { 185 console.log("Parameter error. [" + codeNumber + "]"); 186 } 187 } 188} 189 190``` 191 1926. Configure the `CMakeLists.txt` file. Add the required shared library, that is, `libnet_connection.so`, to `target_link_libraries` in the `CMakeLists.txt` file automatically generated by the project. 193 194Note: As shown in the following figure, `entry` in `add_library` is the modename automatically generated by the project. If you want to change the `modename`, ensure that it is the same as the `.nm_modname` in step 3. 195 196 197 198After the preceding steps, the entire project is set up. Then, you can connect to the device to run the project to view logs. 199 200## **Test Procedure** 201 2021. Connect the device and use DevEco Studio to open the project. 203 2042. Run the project. The following figure is displayed on the device. 205 206> NOTE 207 208- If you click `GetDefaultNet`, you'll obtain the default network ID. 209- If you click `codeNumber`, you'll obtain the status code returned by the API. 210 211 212 2133. Click `GetDefaultNet`. The following log is displayed, as shown below: 214 215 216 2174. Click `codeNumber`. The status code is displayed, as shown below: 218 219 220