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 callback mode. For details about the APIs, see [sms API Reference](../reference/apis/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- System: Linux kernel 21- 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. 22 23## When to Use 24 25Typical application scenarios of network connection management are as follows: 26 27- Subscribing to status changes of the specified network 28- Obtaining the list of all registered networks 29- Querying network connection information based on the data network 30- Resolving the domain name of a network to obtain all IP addresses 31 32The following describes the development procedure specific to each application scenario. 33 34## Available APIs 35 36For the complete list of APIs and example code, see [Network Connection Management](../reference/apis/js-apis-net-connection.md). 37 38| API| Description| 39| ---- | ---- | 40| 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.| 41| getGlobalHttpProxy(callback: AsyncCallback\<HttpProxy>): void;| Obtains the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.| 42| 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.| 43| setAppHttpProxy(httpProxy: HttpProxy): void;| Sets the application-level HTTP proxy configuration of the network.| 44| 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.| 45| 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.| 46| 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.| 47| hasDefaultNet(callback: AsyncCallback\<boolean>): void; |Checks whether the default data network is activated. This API uses an asynchronous callback to return the result.| 48| 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.| 49| 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.| 50| 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.| 51| 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.| 52| 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.| 53| 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.| 54| 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.| 55| enableAirplaneMode(callback: AsyncCallback\<void>): void; | Enables the airplane mode. This API uses an asynchronous callback to return the result.| 56| disableAirplaneMode(callback: AsyncCallback\<void>): void;| Disables the airplane mode. This API uses an asynchronous callback to return the result.| 57| 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.| 58| 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.| 59| 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.| 60| 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.| 61| on(type: 'netAvailable', callback: Callback\<NetHandle>): void; |Subscribes to **netAvailable** events.| 62| on(type: 'netCapabilitiesChange', callback: Callback\<NetCapabilityInfo\>): void; |Subscribes to **netCapabilitiesChange** events.| 63| on(type: 'netConnectionPropertiesChange', callback: Callback\<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void; |Subscribes to **netConnectionPropertiesChange** events.| 64| on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void; |Subscribes to **netBlockStatusChange** events.| 65| on(type: 'netLost', callback: Callback\<NetHandle>): void; |Subscribes to **netLost** events.| 66| on(type: 'netUnavailable', callback: Callback\<void>): void; |Subscribes to **netUnavailable** events.| 67| register(callback: AsyncCallback\<void>): void; |Subscribes to network status changes.| 68| unregister(callback: AsyncCallback\<void>): void; |Unsubscribes from network status changes.| 69 70## Subscribing to Status Changes of the Specified Network 71 721. Declare the required permission: **ohos.permission.GET_NETWORK_INFO**. 73This permission is of the **system\_basic** 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). 74 751. Import the connection namespace from **@ohos.net.connection.d.ts**. 76 772. 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. 78 793. Call **conn.on()** to subscribe to the target event. You must pass in **type** and **callback**. 80 814. Call **conn.register()** to subscribe to network status changes of the specified network. 82 835. 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. 84 856. Call **conn.unregister()** to unsubscribe from the network status changes if required. 86 87```ts 88// Import the connection namespace. 89import connection from '@ohos.net.connection'; 90import { BusinessError } from '@ohos.base'; 91 92let netSpecifier: connection.NetSpecifier = { 93 netCapabilities: { 94 // Assume that the default network is Wi-Fi. If you need to create a cellular network connection, set the network type to CELLULAR. 95 bearerTypes: [connection.NetBearType.BEARER_CELLULAR], 96 // Set the network capability to INTERNET. 97 networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET] 98 }, 99}; 100 101// Set the timeout value to 10s. The default value is 0. 102let timeout = 10 * 1000; 103 104// Create a NetConnection object. 105let conn = connection.createNetConnection(netSpecifier, timeout); 106 107// Register an observer for network status changes. 108conn.register((err: BusinessError, data: void) => { 109 // Subscribe to network status change events. If the network is available, an on_netAvailable event is returned. 110 conn.on('netAvailable', ((data: connection.NetHandle) => { 111 console.log("net is available, netId is " + data.netId); 112 })); 113 114 // Subscribe to network status change events. If the network is unavailable, an on_netUnavailable event is returned. 115 conn.on('netUnavailable', ((data: void) => { 116 console.log("net is unavailable, data is " + JSON.stringify(data)); 117 })); 118}); 119 120// Unregister the observer for network status changes. 121conn.unregister((err: BusinessError, data: void) => { 122}); 123``` 124 125## Obtaining the List of All Registered Networks 126 127### How to Develop 128 1291. Declare the required permission: **ohos.permission.GET_NETWORK_INFO**. 130This permission is of the **system\_basic** 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). 131 1322. Import the connection namespace from **@ohos.net.connection.d.ts**. 133 1343. Call **getAllNets** to obtain the list of all connected networks. 135 136```ts 137// Import the connection namespace. 138import connection from '@ohos.net.connection'; 139import { BusinessError } from '@ohos.base'; 140 141// Construct a singleton object. 142export class GlobalContext { 143 public netList: connection.NetHandle[] = []; 144 private constructor() {} 145 private static instance: GlobalContext; 146 private _objects = new Map<string, Object>(); 147 148 public static getContext(): GlobalContext { 149 if (!GlobalContext.instance) { 150 GlobalContext.instance = new GlobalContext(); 151 } 152 return GlobalContext.instance; 153 } 154 155 getObject(value: string): Object | undefined { 156 return this._objects.get(value); 157 } 158 159 setObject(key: string, objectClass: Object): void { 160 this._objects.set(key, objectClass); 161 } 162} 163 164// Obtain the list of all connected networks. 165connection.getAllNets((err: BusinessError, data: connection.NetHandle[]) => { 166 console.log(JSON.stringify(err)); 167 console.log(JSON.stringify(data)); 168 if (data) { 169 GlobalContext.getContext().netList = data; 170 } 171}) 172``` 173 174## Querying Network Capability Information and Connection Information of Specified Data Network 175 176### How to Develop 177 1781. Declare the required permission: **ohos.permission.GET_NETWORK_INFO**. 179This permission is of the **system\_basic** 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). 180 1812. Import the connection namespace from **@ohos.net.connection.d.ts**. 182 1833. Call **getDefaultNet** to obtain the default data network via **NetHandle** or call **getAllNets** to obtain the list of all connected networks via **Array\<NetHandle>**. 184 1854. 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. 186 1875. Call **getConnectionProperties** to obtain the connection information of the data network specified by **NetHandle**. 188 189```ts 190import connection from '@ohos.net.connection'; 191import { BusinessError } from '@ohos.base'; 192 193// Construct a singleton object. 194export class GlobalContext { 195 public netList: connection.NetHandle[] = []; 196 public netHandle: connection.NetHandle|null = null; 197 private constructor() {} 198 private static instance: GlobalContext; 199 private _objects = new Map<string, Object>(); 200 201 public static getContext(): GlobalContext { 202 if (!GlobalContext.instance) { 203 GlobalContext.instance = new GlobalContext(); 204 } 205 return GlobalContext.instance; 206 } 207 208 getObject(value: string): Object | undefined { 209 return this._objects.get(value); 210 } 211 212 setObject(key: string, objectClass: Object): void { 213 this._objects.set(key, objectClass); 214 } 215} 216 217// Call getDefaultNet to obtain the default data network specified by **NetHandle**. 218connection.getDefaultNet((err: BusinessError, data:connection.NetHandle) => { 219 console.log(JSON.stringify(err)); 220 console.log(JSON.stringify(data)); 221 if (data) { 222 GlobalContext.getContext().netHandle = data; 223 224 // 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. 225 connection.getNetCapabilities(GlobalContext.getContext().netHandle, (err: BusinessError, data: connection.NetCapabilities) => { 226 console.log(JSON.stringify(err)); 227 228 // Obtain the network type via bearerTypes. 229 let bearerTypes: Set<number> = new Set(data.bearerTypes); 230 let bearerTypesNum = Array.from(bearerTypes.values()); 231 for (let item of bearerTypesNum) { 232 if (item == 0) { 233 // Cellular network 234 console.log(JSON.stringify("BEARER_CELLULAR")); 235 } else if (item == 1) { 236 // Wi-Fi network 237 console.log(JSON.stringify("BEARER_WIFI")); 238 } else if (item == 3) { 239 // Ethernet network 240 console.log(JSON.stringify("BEARER_ETHERNET")); 241 } 242 } 243 244 // Obtain the specific network capabilities via networkCap. 245 let itemNumber : Set<number> = new Set(data.networkCap); 246 let dataNumber = Array.from(itemNumber.values()); 247 for (let item of dataNumber) { 248 if (item == 0) { 249 // The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages. 250 console.log(JSON.stringify("NET_CAPABILITY_MMS")); 251 } else if (item == 11) { 252 // The network traffic is not metered. 253 console.log(JSON.stringify("NET_CAPABILITY_NOT_METERED")); 254 } else if (item == 12) { 255 // The network has the Internet access capability, which is set by the network provider. 256 console.log(JSON.stringify("NET_CAPABILITY_INTERNET")); 257 } else if (item == 15) { 258 // The network does not use a Virtual Private Network (VPN). 259 console.log(JSON.stringify("NET_CAPABILITY_NOT_VPN")); 260 } else if (item == 16) { 261 // The Internet access capability of the network is successfully verified by the connection management module. 262 console.log(JSON.stringify("NET_CAPABILITY_VALIDATED")); 263 } 264 } 265 }) 266 } 267}) 268 269// Obtain the connection information of the data network specified by NetHandle. Connection information includes link and route information. 270connection.getConnectionProperties(GlobalContext.getContext().netHandle, (err: BusinessError, data: connection.ConnectionProperties) => { 271 console.log(JSON.stringify(err)); 272 console.log(JSON.stringify(data)); 273}) 274 275// Call getAllNets to obtain the list of all connected networks via Array<NetHandle>. 276connection.getAllNets((err: BusinessError, data: connection.NetHandle[]) => { 277 console.log(JSON.stringify(err)); 278 console.log(JSON.stringify(data)); 279 if (data) { 280 GlobalContext.getContext().netList = data; 281 282 let itemNumber : Set<connection.NetHandle> = new Set(GlobalContext.getContext().netList); 283 let dataNumber = Array.from(itemNumber.values()); 284 for (let item of dataNumber) { 285 // Obtain the network capability information of the network specified by each netHandle on the network list cyclically. 286 connection.getNetCapabilities(item, (err: BusinessError, data: connection.NetCapabilities) => { 287 console.log(JSON.stringify(err)); 288 console.log(JSON.stringify(data)); 289 }) 290 291 // Obtain the connection information of the network specified by each netHandle on the network list cyclically. 292 connection.getConnectionProperties(item, (err: BusinessError, data: connection.ConnectionProperties) => { 293 console.log(JSON.stringify(err)); 294 console.log(JSON.stringify(data)); 295 }) 296 } 297 } 298}) 299``` 300 301## Resolving the domain name of a network to obtain all IP addresses 302 303### How to Develop 304 3051. Declare the required permission: **ohos.permission.INTERNET**. 306This permission is of the **system\_basic** 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). 307 3082. Import the connection namespace from **@ohos.net.connection.d.ts**. 309 3103. Call **getAddressesByName** to use the default network to resolve the host name to obtain the list of all IP addresses. 311 312```ts 313// Import the connection namespace. 314import connection from '@ohos.net.connection'; 315import { BusinessError } from '@ohos.base'; 316 317// Use the default network to resolve the host name to obtain the list of all IP addresses. 318connection.getAddressesByName(this.host, (err: BusinessError, data: connection.NetAddress[]) => { 319 console.log(JSON.stringify(err)); 320 console.log(JSON.stringify(data)); 321}) 322``` 323