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| OH_NetConn_SetPacUrl(const char \*pacUrl) | Sets the URL of the system-level proxy auto-config (PAC) script.| 28| OH_NetConn_GetPacUrl(char \*pacUrl) | Obtains the URL of the system-level PAC script.| 29 30## Development Example 31 32### How to Develop 33 34To 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. 35 36This document describes how to obtain the default active data network as an example. 37 38### Adding Dependencies 39 40**Adding the Dynamic Link Library** 41 42Add the following library to **CMakeLists.txt**. 43 44```txt 45libace_napi.z.so 46libnet_connection.so 47``` 48 49**Including Header Files** 50 51```c 52#include "napi/native_api.h" 53#include "network/netmanager/net_connection.h" 54#include "network/netmanager/net_connection_type.h" 55``` 56 57### Building the Project 58 591. 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. 60 61```C 62// Get the execution results of the default network connection. 63static napi_value GetDefaultNet(napi_env env, napi_callback_info info) 64{ 65 size_t argc = 1; 66 napi_value args[1] = {nullptr}; 67 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 68 int32_t param; 69 napi_get_value_int32(env, args[0], ¶m); 70 71 NetConn_NetHandle netHandle; 72 if (param== 0) { 73 param= OH_NetConn_GetDefaultNet(NULL); 74 } else { 75 param= OH_NetConn_GetDefaultNet(&netHandle); 76 } 77 78 napi_value result; 79 napi_create_int32(env, param, &result); 80 return result; 81} 82 83// Get the ID of the default network connection. 84static napi_value NetId(napi_env env, napi_callback_info info) { 85 int32_t defaultNetId; 86 87 NetConn_NetHandle netHandle; 88 OH_NetConn_GetDefaultNet(&netHandle); 89 defaultNetId = netHandle.netId; // Get the default netId 90 91 napi_value result; 92 napi_create_int32(env, defaultNetId, &result); 93 94 return result; 95} 96``` 97 98> **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. 99 100 1012. Initialize and export the `napi_value` objects encapsulated through **NAPI**, and expose the preceding two functions to JavaScript through external function APIs. 102 103```C 104EXTERN_C_START 105static napi_value Init(napi_env env, napi_value exports) 106{ 107 // Information used to describe an exported attribute. Two properties are defined here: `GetDefaultNet` and `NetId`. 108 napi_property_descriptor desc[] = { 109 {"GetDefaultNet", nullptr, GetDefaultNet, nullptr, nullptr, nullptr, napi_default, nullptr}, 110 {"NetId", nullptr, NetId, nullptr, nullptr, nullptr, napi_default, nullptr}}; 111 napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); 112 return exports; 113} 114EXTERN_C_END 115``` 116 1173. Register the objects successfully initialized in the previous step into the Node.js file by using the `napi_module_register` function of `RegisterEntryModule`. 118 119```C 120static napi_module demoModule = { 121 .nm_version = 1, 122 .nm_flags = 0, 123 .nm_filename = nullptr, 124 .nm_register_func = Init, 125 .nm_modname = "entry", 126 .nm_priv = ((void*)0), 127 .reserved = { 0 }, 128}; 129 130extern "C" __attribute__((constructor)) void RegisterEntryModule(void) 131{ 132 napi_module_register(&demoModule); 133} 134``` 135 1364. Define the types of the two functions in the `index.d.ts ` file of the project. 137 138- The `GetDefaultNet ` function accepts the numeric parameter code and returns a numeric value. 139- The `NetId` function does not accept parameters and returns a numeric value. 140 141```ts 142export const GetDefaultNet: (code: number) => number; 143export const NetId: () => number; 144``` 145 1465. Call the encapsulated APIs in the `index.ets` file. 147 148```ts 149import testNetManager from 'libentry.so'; 150 151@Entry 152@Component 153struct Index { 154 @State message: string = ''; 155 156 build() { 157 Row() { 158 Column() { 159 Text(this.message) 160 .fontSize(50) 161 .fontWeight(FontWeight.Bold) 162 Button('GetDefaultNet').onClick(event => { 163 this.GetDefaultNet(); 164 }) 165 Button('CodeNumber').onClick(event =>{ 166 this.CodeNumber(); 167 }) 168 } 169 .width('100%') 170 } 171 .height('100%') 172 } 173 174 GetDefaultNet() { 175 let netid = testNetManager.NetId(); 176 console.log("The defaultNetId is [" + netid + "]"); 177 } 178 179 CodeNumber() { 180 let testParam = 0; 181 let codeNumber = testNetManager.GetDefaultNet(testParam); 182 if (codeNumber === 0) { 183 console.log("Test success. [" + codeNumber + "]"); 184 } else if (codeNumber === 201) { 185 console.log("Missing permissions. [" + codeNumber + "]"); 186 } else if (codeNumber === 401) { 187 console.log("Parameter error. [" + codeNumber + "]"); 188 } 189 } 190} 191 192``` 193 1946. 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. 195 196Note: 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. 197 198 199 200After the preceding steps, the entire project is set up. Then, you can connect to the device to run the project to view logs. 201 202## **Test Procedure** 203 2041. Connect the device and use DevEco Studio to open the project. 205 2062. Run the project. The following figure is displayed on the device. 207 208> NOTE 209 210- If you click `GetDefaultNet`, you'll obtain the default network ID. 211- If you click `codeNumber`, you'll obtain the status code returned by the API. 212 213 214 2153. Click `GetDefaultNet`. The following log is displayed, as shown below: 216 217 218 2194. Click `codeNumber`. The status code is displayed, as shown below: 220 221 222