1# Network Connection Management
2
3## Introduction
4
5The Network Connection Management module provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution.
6
7> **NOTE**
8> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the promise mode. For details about the APIs, see [API Reference](../reference/apis-network-kit/js-apis-net-connection.md).
9
10## Basic Concepts
11
12- Producer: a provider of data networks, such as Wi-Fi, cellular, and Ethernet.
13- Consumer: a user of data networks, for example, an application or a system service.
14- Network probe: a mechanism used to detect the network availability to prevent the switch from an available network to an unavailable network. The probe type can be binding network detection, DNS detection, HTTP detection, or HTTPS detection.
15- Network selection: a mechanism used to select the optimal network when multiple networks coexist. It is triggered when the network status, network information, or network quality evaluation score changes.
16
17## **Constraints**
18
19- Programming language: JS
20- The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
21
22## When to Use
23
24Typical application scenarios of network connection management are as follows:
25
26- Subscribing to status changes of the specified network
27- Obtaining the list of all registered networks
28- Querying network connection information based on the data network
29- Resolving the domain name of a network to obtain all IP addresses
30
31The following describes the development procedure specific to each application scenario.
32
33## Available APIs
34
35For the complete list of APIs and example code, see [Network Connection Management](../reference/apis-network-kit/js-apis-net-connection.md).
36
37| API| Description|
38| ---- | ---- |
39| getDefaultNet(callback: AsyncCallback\<NetHandle>): void; |Creates a **NetHandle** object that contains the **netId** of the default network. This API uses an asynchronous callback to return the result.|
40| <!--DelRow--> getGlobalHttpProxy(callback: AsyncCallback\<HttpProxy>): void;| Obtains the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.|
41| <!--DelRow--> setGlobalHttpProxy(httpProxy: HttpProxy, callback: AsyncCallback\<void>): void;| Sets the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.|
42| setAppHttpProxy(httpProxy: HttpProxy): void;| Sets the application-level HTTP proxy configuration of the network.|
43| getAppNet(callback: AsyncCallback\<NetHandle>): void;| Obtains a **NetHandle** object that contains the **netId** of the network bound to the application. This API uses an asynchronous callback to return the result.|
44| setAppNet(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Binds an application to the specified network. The application can access the external network only through this network. This API uses an asynchronous callback to return the result.|
45| getDefaultNetSync(): NetHandle; |Obtains the default active data network in synchronous mode. You can use **getNetCapabilities** to obtain information such as the network type and capabilities.|
46| hasDefaultNet(callback: AsyncCallback\<boolean>): void; |Checks whether the default data network is activated. This API uses an asynchronous callback to return the result.|
47| getAllNets(callback: AsyncCallback\<Array\<NetHandle>>): void;| Obtains the list of **NetHandle** objects of the connected network. This API uses an asynchronous callback to return the result.|
48| getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<ConnectionProperties>): void; |Obtains network connection information of the network corresponding to the **netHandle**. This API uses an asynchronous callback to return the result.|
49| getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilities>): void; |Obtains capability information of the network corresponding to the **netHandle**. This API uses an asynchronous callback to return the result.|
50| isDefaultNetMetered(callback: AsyncCallback\<boolean>): void; |Checks whether the data traffic usage on the current network is metered. This API uses an asynchronous callback to return the result.|
51| reportNetConnected(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.|
52| reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.|
53| getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void; |Obtains all IP addresses of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.|
54| <!--DelRow--> enableAirplaneMode(callback: AsyncCallback\<void>): void; | Enables the airplane mode. This API uses an asynchronous callback to return the result.|
55| <!--DelRow--> disableAirplaneMode(callback: AsyncCallback\<void>): void;| Disables the airplane mode. This API uses an asynchronous callback to return the result.|
56| createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection; | Creates a **NetConnection** object. **netSpecifier** specifies the network, and **timeout** specifies the timeout interval in ms. **timeout** is configurable only when **netSpecifier** is specified. If neither of them is present, the default network is used.|
57| bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>): void; | Binds a **TCPSocket** or **UDPSocket** to the current network. This API uses an asynchronous callback to return the result.|
58| getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void; |Obtains all IP addresses of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.|
59| getAddressByName(host: string, callback: AsyncCallback\<NetAddress>): void; |Obtains an IP address of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.|
60| on(type: 'netAvailable', callback: Callback\<NetHandle>): void;                   |Subscribes to **netAvailable** events.|
61| on(type: 'netCapabilitiesChange', callback: Callback\<NetCapabilityInfo\>): void; |Subscribes to **netCapabilitiesChange** events.|
62| on(type: 'netConnectionPropertiesChange', callback: Callback\<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void; |Subscribes to **netConnectionPropertiesChange** events.|
63| on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void; |Subscribes to **netBlockStatusChange** events.|
64| on(type: 'netLost', callback: Callback\<NetHandle>): void; |Subscribes to **netLost** events.|
65| on(type: 'netUnavailable', callback: Callback\<void>): void; |Subscribes to **netUnavailable** events.|
66| register(callback: AsyncCallback\<void>): void; |Subscribes to network status changes.|
67| unregister(callback: AsyncCallback\<void>): void; |Unsubscribes from network status changes.|
68
69## Subscribing to Status Changes of the Specified Network
70
711. Declare the required permission: **ohos.permission.GET_NETWORK_INFO**.
72This permission is of the **normal** level. Before applying for the permission, ensure that the [basic principles for permission management](../security/AccessToken/app-permission-mgmt-overview.md#basic-principles-for-using-permissions) are met. Declare the permissions required by your application. For details, see [Declaring Permissions in the Configuration File](accesstoken-guidelines.md#declaring-permissions-in-the configuration-file).
73
741. Import the **connection** namespace from **@kit.NetworkKit**.
75
762. Call **createNetConnection()** to create a **NetConnection** object. You can specify the network type, capability, and timeout interval. If you do not specify parameters, the default values will be used.
77
783. Call **conn.on()** to subscribe to the target event. You must pass in **type** and **callback**.
79
804. Call **conn.register()** to subscribe to network status changes of the specified network.
81
825. When the network is available, the callback will be invoked to return the **netAvailable** event. When the network is unavailable, the callback will be invoked to return the **netUnavailable** event.
83
846. Call **conn.unregister()** to unsubscribe from the network status changes if required.
85
86```ts
87// Import the connection namespace.
88import { connection } from '@kit.NetworkKit';
89import { BusinessError } from '@kit.BasicServicesKit';
90
91let netSpecifier: connection.NetSpecifier = {
92  netCapabilities: {
93    // Assume that the default network is Wi-Fi. If you need to create a cellular network connection, set the network type to CELLULAR.
94    bearerTypes: [connection.NetBearType.BEARER_CELLULAR],
95    // Set the network capability to INTERNET.
96    networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET]
97  },
98};
99
100// Set the timeout value to 10s. The default value is 0.
101let timeout = 10 * 1000;
102
103// Create a NetConnection object.
104let conn = connection.createNetConnection(netSpecifier, timeout);
105
106// Register an observer for network status changes.
107conn.register((err: BusinessError, data: void) => {
108  console.log(JSON.stringify(err));
109});
110
111// Listen to network status change events. If the network is available, an on_netAvailable event is returned.
112conn.on('netAvailable', ((data: connection.NetHandle) => {
113  console.log("net is available, netId is " + data.netId);
114}));
115
116// Listen to network status change events. If the network is unavailable, an on_netUnavailable event is returned.
117conn.on('netUnavailable', ((data: void) => {
118  console.log("net is unavailable, data is " + JSON.stringify(data));
119}));
120
121// Unregister the observer for network status changes.
122conn.unregister((err: BusinessError, data: void) => {
123});
124```
125
126## Obtaining the List of All Registered Networks
127
1281. Declare the required permission: **ohos.permission.GET_NETWORK_INFO**.
129This permission is of the **normal** level. Before applying for the permission, ensure that the [basic principles for permission management](../security/AccessToken/app-permission-mgmt-overview.md#basic-principles-for-using-permissions) are met. Declare the permissions required by your application. For details, see [Declaring Permissions in the Configuration File](accesstoken-guidelines.md#declaring-permissions-in-the configuration-file).
130
1312. Import the **connection** namespace from **@kit.NetworkKit**.
132
1333. Call **getAllNets** to obtain the list of all connected networks.
134
135```ts
136// Import the connection namespace.
137import { connection } from '@kit.NetworkKit';
138import { BusinessError } from '@kit.BasicServicesKit';
139
140// Construct a singleton object.
141export class GlobalContext {
142  public netList: connection.NetHandle[] = [];
143  private constructor() {}
144  private static instance: GlobalContext;
145  private _objects = new Map<string, Object>();
146
147  public static getContext(): GlobalContext {
148    if (!GlobalContext.instance) {
149      GlobalContext.instance = new GlobalContext();
150    }
151    return GlobalContext.instance;
152  }
153
154  getObject(value: string): Object | undefined {
155    return this._objects.get(value);
156  }
157
158  setObject(key: string, objectClass: Object): void {
159    this._objects.set(key, objectClass);
160  }
161}
162
163// Obtain the list of all connected networks.
164connection.getAllNets().then((data: connection.NetHandle[]) => {
165  console.info("Succeeded to get data: " + JSON.stringify(data));
166  if (data) {
167    GlobalContext.getContext().netList = data;
168  }
169});
170```
171
172## Querying Network Capability Information and Connection Information of Specified Data Network
173
1741. Declare the required permission: **ohos.permission.GET_NETWORK_INFO**.
175This permission is of the **normal** level. Before applying for the permission, ensure that the [basic principles for permission management](../security/AccessToken/app-permission-mgmt-overview.md#basic-principles-for-using-permissions) are met. Declare the permissions required by your application. For details, see [Declaring Permissions in the Configuration File](accesstoken-guidelines.md#declaring-permissions-in-the configuration-file).
176
1772. Import the **connection** namespace from **@kit.NetworkKit**.
178
1793. Call **getDefaultNet** to obtain the default data network via **NetHandle** or call **getAllNets** to obtain the list of all connected networks via **Array\<NetHandle>**.
180
1814. Call **getNetCapabilities** to obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type (cellular, Wi-Fi, or Ethernet network) and the specific network capabilities.
182
1835. Call **getConnectionProperties** to obtain the connection information of the data network specified by **NetHandle**.
184
185```ts
186import { connection } from '@kit.NetworkKit';
187import { BusinessError } from '@kit.BasicServicesKit';
188
189// Construct a singleton object.
190export class GlobalContext {
191  public netList: connection.NetHandle[] = [];
192  public netHandle: connection.NetHandle|null = null;
193  private constructor() {}
194  private static instance: GlobalContext;
195  private _objects = new Map<string, Object>();
196
197  public static getContext(): GlobalContext {
198    if (!GlobalContext.instance) {
199      GlobalContext.instance = new GlobalContext();
200    }
201    return GlobalContext.instance;
202  }
203
204  getObject(value: string): Object | undefined {
205    return this._objects.get(value);
206  }
207
208  setObject(key: string, objectClass: Object): void {
209    this._objects.set(key, objectClass);
210  }
211}
212
213// Call getDefaultNet to obtain the default data network specified by **NetHandle**.
214connection.getDefaultNet().then((data:connection.NetHandle) => {
215  if (data.netId == 0) {
216    // If the obtained netid of netHandler is 0 when no default network is specified, an exception has occurred and extra processing is needed.
217    return;
218  }
219  if (data) {
220    console.info("getDefaultNet get data: " + JSON.stringify(data));
221    GlobalContext.getContext().netHandle = data;
222    // Obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type and specific network capabilities.
223    connection.getNetCapabilities(GlobalContext.getContext().netHandle).then(
224      (data: connection.NetCapabilities) => {
225      console.info("getNetCapabilities get data: " + JSON.stringify(data));
226      // Obtain the network type via bearerTypes.
227      let bearerTypes: Set<number> = new Set(data.bearerTypes);
228      let bearerTypesNum = Array.from(bearerTypes.values());
229      for (let item of bearerTypesNum) {
230        if (item == 0) {
231          // Cellular network
232          console.log(JSON.stringify("BEARER_CELLULAR"));
233        } else if (item == 1) {
234          // Wi-Fi network
235          console.log(JSON.stringify("BEARER_WIFI"));
236        } else if (item == 3) {
237          // Ethernet network
238          console.log(JSON.stringify("BEARER_ETHERNET"));
239        }
240      }
241
242      // Obtain the specific network capabilities via networkCap.
243      let itemNumber : Set<number> = new Set(data.networkCap);
244      let dataNumber = Array.from(itemNumber.values());
245      for (let item of dataNumber) {
246        if (item == 0) {
247          // The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.
248          console.log(JSON.stringify("NET_CAPABILITY_MMS"));
249        } else if (item == 11) {
250          // The network traffic is not metered.
251          console.log(JSON.stringify("NET_CAPABILITY_NOT_METERED"));
252        } else if (item == 12) {
253          // The network has the Internet access capability, which is set by the network provider.
254          console.log(JSON.stringify("NET_CAPABILITY_INTERNET"));
255        } else if (item == 15) {
256          // The network does not use a Virtual Private Network (VPN).
257          console.log(JSON.stringify("NET_CAPABILITY_NOT_VPN"));
258        } else if (item == 16) {
259          // The Internet access capability of the network is successfully verified by the connection management module.
260          console.log(JSON.stringify("NET_CAPABILITY_VALIDATED"));
261        }
262      }
263    })
264  }
265});
266
267// Obtain the connection information of the data network specified by NetHandle. Connection information includes link and route information.
268connection.getConnectionProperties(GlobalContext.getContext().netHandle).then((data: connection.ConnectionProperties) => {
269  console.info("getConnectionProperties get data: " + JSON.stringify(data));
270})
271
272// Call getAllNets to obtain the list of all connected networks via Array<NetHandle>.
273connection.getAllNets().then((data: connection.NetHandle[]) => {
274  console.info("getAllNets get data: " + JSON.stringify(data));
275  if (data) {
276    GlobalContext.getContext().netList = data;
277
278    let itemNumber : Set<connection.NetHandle> = new Set(GlobalContext.getContext().netList);
279    let dataNumber = Array.from(itemNumber.values());
280    for (let item of dataNumber) {
281      // Obtain the network capability information of the network specified by each netHandle on the network list cyclically.
282      connection.getNetCapabilities(item).then((data: connection.NetCapabilities) => {
283        console.info("getNetCapabilities get data: " + JSON.stringify(data));
284      })
285
286      // Obtain the connection information of the network specified by each netHandle on the network list cyclically.
287      connection.getConnectionProperties(item).then((data: connection.ConnectionProperties) => {
288        console.info("getConnectionProperties get data: " + JSON.stringify(data));
289      })
290    }
291  }
292})
293```
294
295## Resolving the domain name of a network to obtain all IP addresses
296
2971. Declare the required permission: **ohos.permission.INTERNET**.
298This permission is of the **normal** level. Before applying for the permission, ensure that the [basic principles for permission management](../security/AccessToken/app-permission-mgmt-overview.md#basic-principles-for-using-permissions) are met. Declare the permissions required by your application. For details, see [Declaring Permissions in the Configuration File](accesstoken-guidelines.md#declaring-permissions-in-the configuration-file).
299
3002. Import the **connection** namespace from **@kit.NetworkKit**.
301
3023. Call **getAddressesByName** to use the default network to resolve the host name to obtain the list of all IP addresses.
303
304```ts
305// Import the connection namespace.
306import { connection } from '@kit.NetworkKit';
307import { BusinessError } from '@kit.BasicServicesKit';
308
309// Use the default network to resolve the host name to obtain the list of all IP addresses.
310connection.getAddressesByName("xxxx").then((data: connection.NetAddress[]) => {
311  console.info("Succeeded to get data: " + JSON.stringify(data));
312});
313```
314