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