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 38For details about other APIs, see the [Complete Sample Code](https://gitee.com/openharmony/applications_app_samples/tree/master/code/DocsSample/NetWork_Kit/NetWorkKit_NetManager/NetConnection_Exploitation_case). 39 40### Adding Dependencies 41 42**Adding the Dynamic Link Library** 43 44Add the following library to **CMakeLists.txt**. 45 46```txt 47libace_napi.z.so 48libnet_connection.so 49``` 50 51**Including Header Files** 52 53```c 54#include "napi/native_api.h" 55#include "network/netmanager/net_connection.h" 56#include "network/netmanager/net_connection_type.h" 57``` 58 59### Building the Project 60 611. 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. 62 63```C 64// Get the execution results of the default network connection. 65static napi_value GetDefaultNet(napi_env env, napi_callback_info info) 66{ 67 size_t argc = 1; 68 napi_value args[1] = {nullptr}; 69 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 70 int32_t param; 71 napi_get_value_int32(env, args[0], ¶m); 72 73 NetConn_NetHandle netHandle; 74 if (param== 0) { 75 param= OH_NetConn_GetDefaultNet(NULL); 76 } else { 77 param= OH_NetConn_GetDefaultNet(&netHandle); 78 } 79 80 napi_value result; 81 napi_create_int32(env, param, &result); 82 return result; 83} 84 85// Get the ID of the default network connection. 86static napi_value NetId(napi_env env, napi_callback_info info) { 87 int32_t defaultNetId; 88 89 NetConn_NetHandle netHandle; 90 OH_NetConn_GetDefaultNet(&netHandle); 91 defaultNetId = netHandle.netId; // Get the default netId 92 93 napi_value result; 94 napi_create_int32(env, defaultNetId, &result); 95 96 return result; 97} 98``` 99 100> **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. 101 102 1032. Initialize and export the `napi_value` objects encapsulated through **NAPI**, and expose the preceding two functions to JavaScript through external function APIs. 104 105```C 106EXTERN_C_START 107static napi_value Init(napi_env env, napi_value exports) 108{ 109 // Information used to describe an exported attribute. Two properties are defined here: `GetDefaultNet` and `NetId`. 110 napi_property_descriptor desc[] = { 111 {"GetDefaultNet", nullptr, GetDefaultNet, nullptr, nullptr, nullptr, napi_default, nullptr}, 112 {"NetId", nullptr, NetId, nullptr, nullptr, nullptr, napi_default, nullptr}}; 113 napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); 114 return exports; 115} 116EXTERN_C_END 117``` 118 1193. Register the objects successfully initialized in the previous step into the Node.js file by using the `napi_module_register` function of `RegisterEntryModule`. 120 121```C 122static napi_module demoModule = { 123 .nm_version = 1, 124 .nm_flags = 0, 125 .nm_filename = nullptr, 126 .nm_register_func = Init, 127 .nm_modname = "entry", 128 .nm_priv = ((void*)0), 129 .reserved = { 0 }, 130}; 131 132extern "C" __attribute__((constructor)) void RegisterEntryModule(void) 133{ 134 napi_module_register(&demoModule); 135} 136``` 137 1384. Define the types of the two functions in the `index.d.ts ` file of the project. 139 140- The `GetDefaultNet ` function accepts the numeric parameter code and returns a numeric value. 141- The `NetId` function does not accept parameters and returns a numeric value. 142 143```ts 144export const GetDefaultNet: (code: number) => number; 145export const NetId: () => number; 146``` 147 1485. Call the encapsulated APIs in the `index.ets` file. 149 150```ts 151import testNetManager from 'libentry.so'; 152 153@Entry 154@Component 155struct Index { 156 @State message: string = ''; 157 158 build() { 159 Row() { 160 Column() { 161 Text(this.message) 162 .fontSize(50) 163 .fontWeight(FontWeight.Bold) 164 Button('GetDefaultNet').onClick(event => { 165 this.GetDefaultNet(); 166 }) 167 Button('CodeNumber').onClick(event =>{ 168 this.CodeNumber(); 169 }) 170 } 171 .width('100%') 172 } 173 .height('100%') 174 } 175 176 GetDefaultNet() { 177 let netid = testNetManager.NetId(); 178 console.log("The defaultNetId is [" + netid + "]"); 179 } 180 181 CodeNumber() { 182 let testParam = 0; 183 let codeNumber = testNetManager.GetDefaultNet(testParam); 184 if (codeNumber === 0) { 185 console.log("Test success. [" + codeNumber + "]"); 186 } else if (codeNumber === 201) { 187 console.log("Missing permissions. [" + codeNumber + "]"); 188 } else if (codeNumber === 401) { 189 console.log("Parameter error. [" + codeNumber + "]"); 190 } 191 } 192} 193 194``` 195 1966. 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. 197 198As shown in the following figure, `entry` in `add_library` is the `modename` automatically generated by the project. If you want to change its value, ensure that it is the same as the `.nm_modname` in step 3. 199 200 201 202After the preceding steps, the entire project is set up. Then, you can connect to the device to run the project to view logs. 203 204## **Test Procedure** 205 2061. Connect the device and use DevEco Studio to open the project. 207 2082. Run the project. The following figure is displayed on the device. 209 210> NOTE 211 212- If you click `GetDefaultNet`, you'll obtain the default network ID. 213- If you click `codeNumber`, you'll obtain the status code returned by the API. 214 215 216 2173. Click `GetDefaultNet`. The following log is displayed, as shown below: 218 219 220 2214. Click `codeNumber`. The status code is displayed, as shown below: 222 223 224