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