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