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: C++ and 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| Type| API| Description| 39| ---- | ---- | ---- | 40| ohos.net.connection | function 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| ohos.net.connection | function getGlobalHttpProxy<sup>10+</sup>(callback: AsyncCallback\<HttpProxy>): void;| Obtains the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.| 42| ohos.net.connection | function setGlobalHttpProxy<sup>10+</sup>(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| ohos.net.connection | function getAppNet<sup>9+</sup>(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| ohos.net.connection | function setAppNet<sup>9+</sup>(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| ohos.net.connection | function getDefaultNetSync<sup>9+</sup>(): 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| ohos.net.connection | function hasDefaultNet(callback: AsyncCallback\<boolean>): void; |Checks whether the default network is available. This API uses an asynchronous callback to return the result.| 47| ohos.net.connection | function 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| ohos.net.connection | function getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<ConnectionProperties>): void; |Obtains link information of the default network. This API uses an asynchronous callback to return the result.| 49| ohos.net.connection | function getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilities>): void; |Obtains the capability set of the default network. This API uses an asynchronous callback to return the result.| 50| ohos.net.connection | function isDefaultNetMetered<sup>9+</sup>(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| ohos.net.connection | function 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| ohos.net.connection | function 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| ohos.net.connection | function 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| ohos.net.connection | function enableAirplaneMode(callback: AsyncCallback\<void>): void; | Enables the airplane mode. This API uses an asynchronous callback to return the result.| 55| ohos.net.connection | function disableAirplaneMode(callback: AsyncCallback\<void>): void;| Disables the airplane mode. This API uses an asynchronous callback to return the result.| 56| ohos.net.connection | function 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| ohos.net.connection.NetHandle | 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| ohos.net.connection.NetHandle | getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void; |Obtains all IP addresses of the default network by resolving the domain name. This API uses an asynchronous callback to return the result.| 59| ohos.net.connection.NetHandle | 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| ohos.net.connection.NetConnection | on(type: 'netAvailable', callback: Callback\<NetHandle>): void; |Subscribes to **netAvailable** events.| 61| ohos.net.connection.NetConnection | on(type: 'netCapabilitiesChange', callback: Callback\<{ netHandle: NetHandle, netCap: NetCapabilities }>): void; |Subscribes to **netCapabilitiesChange** events.| 62| ohos.net.connection.NetConnection | on(type: 'netConnectionPropertiesChange', callback: Callback\<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void; |Subscribes to **netConnectionPropertiesChange** events.| 63| ohos.net.connection.NetConnection | on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void; |Subscribes to **netBlockStatusChange** events.| 64| ohos.net.connection.NetConnection | on(type: 'netLost', callback: Callback\<NetHandle>): void; |Subscribes to **netLost** events.| 65| ohos.net.connection.NetConnection | on(type: 'netUnavailable', callback: Callback\<void>): void; |Subscribes to **netUnavailable** events.| 66| ohos.net.connection.NetConnection | register(callback: AsyncCallback\<void>): void; |Registers an observer for the default network or the network specified in **createNetConnection**.| 67| ohos.net.connection.NetConnection | unregister(callback: AsyncCallback\<void>): void; |Unregisters the observer for the default network or the network specified in **createNetConnection**.| 68 69## Subscribing to Status Changes of the Specified Network 70 711. Import the connection namespace from **@ohos.net.connection.d.ts**. 72 732. 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. 74 753. Call **conn.on()** to subscribe to the target event. You must pass in **type** and **callback**. 76 774. Call **conn.register()** to subscribe to network status changes of the specified network. 78 795. 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. 80 816. Call **conn.unregister()** to unsubscribe from the network status changes if required. 82 83```ts 84// Import the connection namespace. 85import connection from '@ohos.net.connection' 86import { BusinessError } from '@ohos.base'; 87 88let netSpecifier: connection.NetSpecifier = { 89 netCapabilities: { 90 // Assume that the default network is Wi-Fi. If you need to create a cellular network connection, set the network type to CELLULAR. 91 bearerTypes: [connection.NetBearType.BEARER_CELLULAR], 92 // Set the network capability to INTERNET. 93 networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET] 94 }, 95}; 96 97// Set the timeout value to 10s. The default value is 0. 98let timeout = 10 * 1000; 99 100// Create a NetConnection object. 101let conn = connection.createNetConnection(netSpecifier, timeout); 102 103// Listen to network status change events. If the network is available, an on_netAvailable event is returned. 104conn.on('netAvailable', ((data: connection.NetHandle) => { 105 console.log("net is available, netId is " + data.netId); 106})); 107 108// Listen to network status change events. If the network is unavailable, an on_netUnavailable event is returned. 109conn.on('netUnavailable', ((data: void) => { 110 console.log("net is unavailable, data is " + JSON.stringify(data)); 111})); 112 113// Register an observer for network status changes. 114conn.register((err: BusinessError, data: void) => { 115}); 116 117// Unregister the observer for network status changes. 118conn.unregister((err: BusinessError, data: void) => { 119}); 120``` 121 122## Obtaining the List of All Registered Networks 123 124### How to Develop 125 1261. Import the connection namespace from **@ohos.net.connection.d.ts**. 127 1282. Call **getAllNets** to obtain the list of all connected networks. 129 130```ts 131// Import the connection namespace. 132import connection from '@ohos.net.connection' 133import { BusinessError } from '@ohos.base' 134 135// Construct a singleton object. 136export class GlobalContext { 137 public netList: connection.NetHandle[] = []; 138 private constructor() {} 139 private static instance: GlobalContext; 140 private _objects = new Map<string, Object>(); 141 142 public static getContext(): GlobalContext { 143 if (!GlobalContext.instance) { 144 GlobalContext.instance = new GlobalContext(); 145 } 146 return GlobalContext.instance; 147 } 148 149 getObject(value: string): Object | undefined { 150 return this._objects.get(value); 151 } 152 153 setObject(key: string, objectClass: Object): void { 154 this._objects.set(key, objectClass); 155 } 156} 157 158// Obtain the list of all connected networks. 159connection.getAllNets((err: BusinessError, data: connection.NetHandle[]) => { 160 console.log(JSON.stringify(err)); 161 console.log(JSON.stringify(data)); 162 if (data) { 163 GlobalContext.getContext().netList = data; 164 } 165}) 166``` 167 168## Querying Network Capability Information and Connection Information of Specified Data Network 169 170### How to Develop 171 1721. Import the connection namespace from **@ohos.net.connection.d.ts**. 173 1742. Call **getDefaultNet** to obtain the default data network via **NetHandle** or call **getAllNets** to obtain the list of all connected networks via **Array\<NetHandle>**. 175 1763. 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. 177 1784. Call **getConnectionProperties** to obtain the connection information of the data network specified by **NetHandle**. 179 180```ts 181import connection from '@ohos.net.connection' 182import { BusinessError } from '@ohos.base'; 183 184// Construct a singleton object. 185export class GlobalContext { 186 public netList: connection.NetHandle[] = []; 187 public netHandle: connection.NetHandle|null = null; 188 private constructor() {} 189 private static instance: GlobalContext; 190 private _objects = new Map<string, Object>(); 191 192 public static getContext(): GlobalContext { 193 if (!GlobalContext.instance) { 194 GlobalContext.instance = new GlobalContext(); 195 } 196 return GlobalContext.instance; 197 } 198 199 getObject(value: string): Object | undefined { 200 return this._objects.get(value); 201 } 202 203 setObject(key: string, objectClass: Object): void { 204 this._objects.set(key, objectClass); 205 } 206} 207 208// Call getDefaultNet to obtain the default data network specified by **NetHandle**. 209connection.getDefaultNet((err: BusinessError, data:connection.NetHandle) => { 210 console.log(JSON.stringify(err)); 211 console.log(JSON.stringify(data)); 212 if (data) { 213 GlobalContext.getContext().netHandle = data; 214 } 215}) 216 217// 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. 218connection.getNetCapabilities(GlobalContext.getContext().netHandle, (err: BusinessError, data: connection.NetCapabilities) => { 219 console.log(JSON.stringify(err)); 220 221 // Obtain the network type via bearerTypes. 222 let bearerTypes: Set<number> = new Set(data.bearerTypes); 223 let bearerTypesNum = Array.from(bearerTypes.values()); 224 for (let item of bearerTypesNum) { 225 if (item == 0) { 226 // Cellular network 227 console.log(JSON.stringify("BEARER_CELLULAR")); 228 } else if (item == 1) { 229 // Wi-Fi network 230 console.log(JSON.stringify("BEARER_WIFI")); 231 } else if (item == 3) { 232 // Ethernet network 233 console.log(JSON.stringify("BEARER_ETHERNET")); 234 } 235 } 236 237 // Obtain the specific network capabilities via networkCap. 238 let itemNumber : Set<number> = new Set([0, 11, 12, 15, 16]); 239 let dataNumber = Array.from(itemNumber.values()); 240 for (let item of dataNumber) { 241 if (item == 0) { 242 // The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages. 243 console.log(JSON.stringify("NET_CAPABILITY_MMS")); 244 } else if (item == 11) { 245 // The network traffic is not metered. 246 console.log(JSON.stringify("NET_CAPABILITY_NOT_METERED")); 247 } else if (item == 12) { 248 // The network has the Internet access capability, which is set by the network provider. 249 console.log(JSON.stringify("NET_CAPABILITY_INTERNET")); 250 } else if (item == 15) { 251 // The network does not use a Virtual Private Network (VPN). 252 console.log(JSON.stringify("NET_CAPABILITY_NOT_VPN")); 253 } else if (item == 16) { 254 // The Internet access capability of the network is successfully verified by the connection management module. 255 console.log(JSON.stringify("NET_CAPABILITY_VALIDATED")); 256 } 257 } 258}) 259 260// Obtain the connection information of the data network specified by NetHandle. Connection information includes link and route information. 261connection.getConnectionProperties(GlobalContext.getContext().netHandle, (err: BusinessError, data: connection.ConnectionProperties) => { 262 console.log(JSON.stringify(err)); 263 console.log(JSON.stringify(data)); 264}) 265 266// Call getAllNets to obtain the list of all connected networks via Array<NetHandle>. 267connection.getAllNets((err: BusinessError, data: connection.NetHandle[]) => { 268 console.log(JSON.stringify(err)); 269 console.log(JSON.stringify(data)); 270 if (data) { 271 GlobalContext.getContext().netList = data; 272 } 273}) 274 275let itemNumber : Set<connection.NetHandle> = new Set(GlobalContext.getContext().netList); 276let dataNumber = Array.from(itemNumber.values()); 277for (let item of dataNumber) { 278 // Obtain the network capability information of the network specified by each netHandle on the network list cyclically. 279 connection.getNetCapabilities(item, (err: BusinessError, data: connection.NetCapabilities) => { 280 console.log(JSON.stringify(err)); 281 console.log(JSON.stringify(data)); 282 }) 283 284 // Obtain the connection information of the network specified by each netHandle on the network list cyclically. 285 connection.getConnectionProperties(item, (err: BusinessError, data: connection.ConnectionProperties) => { 286 console.log(JSON.stringify(err)); 287 console.log(JSON.stringify(data)); 288 }) 289} 290``` 291 292## Resolving the domain name of a network to obtain all IP addresses 293 294### How to Develop 295 2961. Import the connection namespace from **@ohos.net.connection.d.ts**. 297 2982. Call **getAddressesByName** to use the default network to resolve the host name to obtain the list of all IP addresses. 299 300```ts 301 // Import the connection namespace. 302import connection from '@ohos.net.connection' 303import { BusinessError } from '@ohos.base' 304 305// Use the default network to resolve the host name to obtain the list of all IP addresses. 306connection.getAddressesByName(this.host, (err: BusinessError, data: connection.NetAddress[]) => { 307 console.log(JSON.stringify(err)); 308 console.log(JSON.stringify(data)); 309}) 310``` 311