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> 9> 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). 10 11## Basic Concepts 12 13- Producer: a provider of data networks, such as Wi-Fi, cellular, and Ethernet. 14- Consumer: a user of data networks, for example, an application or a system service. 15- 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. 16- 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. 17 18## **Constraints** 19 20- Programming language: JS 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-network-kit/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| <!--DelRow--> getGlobalHttpProxy(callback: AsyncCallback\<HttpProxy>): void;| Obtains the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.| 42| <!--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.| 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 **netAvailable** 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 **netAvailable** 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| <!--DelRow--> enableAirplaneMode(callback: AsyncCallback\<void>): void; | Enables the airplane mode. This API uses an asynchronous callback to return the result.| 56| <!--DelRow--> 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 to be concerned. **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| 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; |Registers a listener for **netBlockStatusChange** events. This API uses an asynchronous callback to return the result.| 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 742. Import the **connection** namespace from **@kit.NetworkKit**. 75 763. Call [createNetConnection](../reference/apis-network-kit/js-apis-net-connection.md#connectioncreatenetconnection) 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 784. Call [on()](../reference/apis-network-kit/js-apis-net-connection.md#onnetavailable) to subscribe to desired events. You must pass in **type** and **callback**. 79 805. Call [register()](../reference/apis-network-kit/js-apis-net-connection.md#register) to subscribe to network status changes of the specified network. 81 826. 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 847. Call [unregister()](../reference/apis-network-kit/js-apis-net-connection.md#unregister) to unsubscribe from the network status changes. 85 86```ts 87// Import the required namespaces. 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// Subscribe 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// Subscribe 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## Monitoring Changes of the Default Network and Re-establishing the Network Connection 127 128Depending on the current network status and network quality, the default network may change, for example: 1291. Switching the default network to the cellular network when the Wi-Fi signal is weak 1302. Switching the default network to the Wi-Fi network when the cellular network signal is weak 1313. Switching the default network to the cellular network when the Wi-Fi network is disabled 1324. Switching the default network to the Wi-Fi network when the cellular network is disabled 1335. Switching the default network to another Wi-Fi network when the Wi-Fi signal is weak (cross-network scenario) 1346. Switching the default network to cellular Wi-Fi network when the cellular signal is weak (cross-network scenario) 135 136The following describes how to monitor changes of the default network and migrate application packets to the new default network. 137 138### Monitoring Changes of the Default Network 139 140```ts 141import { connection } from '@kit.NetworkKit'; 142 143async function test() { 144 const netConnection = connection.createNetConnection(); 145 146 /* Listen for changes of the default network */ 147 netConnection.on('netAvailable', (data: connection.NetHandle) => { 148 console.log(JSON.stringify(data)); 149 }); 150} 151``` 152 153### Re-establishing the Network Connection When the Default Network Is Changed 154 155#### Original Network Connection Established via the HTTP Module 156 157If the original network connection is established through the HTTP module, the socket is not closed immediately after the default network is changed and a new network connection is set up. The reason is that the HTTP module does not provide the **Close** API for closing a socket. Therefore, use Remote Communication Kit to re-establish a network connection. 158 159#### Original Network Connection Established via Remote Communication Kit 160 161```ts 162import { rcp } from '@kit.RemoteCommunicationKit'; 163import { connection } from '@kit.NetworkKit'; 164import { BusinessError } from '@kit.BasicServicesKit'; 165 166let session = rcp.createSession(); 167 168async function useRcp() { 169 /* Create an RCP request */ 170 try { 171 const request = await session.get('https://www.example.com'); 172 console.info(request.statusCode.toString()); 173 } catch (e) { 174 console.error(e.code.toString()); 175 } 176} 177 178async function rcpTest() { 179 const netConnection = connection.createNetConnection(); 180 netConnection.on('netAvailable', async (netHandle: connection.NetHandle) => { 181 /* Re-establish a session when the default network is changed */ 182 session.close(); 183 session = rcp.createSession(); 184 useRcp(); 185 }); 186 try { 187 netConnection.register(() => { 188 }); 189 useRcp(); 190 } catch (e) { 191 console.error(e.code.toString()); 192 } 193} 194``` 195 196#### Original Network Connection Established via the Socket Module 197 198```ts 199import { connection, socket } from '@kit.NetworkKit'; 200import { BusinessError } from '@kit.BasicServicesKit'; 201 202let sock: socket.TCPSocket = socket.constructTCPSocketInstance(); 203 204async function useSocket() { 205 let tcpConnectOptions: socket.TCPConnectOptions = { 206 address: { 207 address: '192.168.xx.xxx', 208 port: 8080 209 }, 210 timeout: 6000 211 } 212 213 /* Set up a socket connection */ 214 sock.connect(tcpConnectOptions, (err: BusinessError) => { 215 if (err) { 216 console.error('connect fail'); 217 return; 218 } 219 console.log('connect success'); 220 221 /* Send data over the socket */ 222 let tcpSendOptions: socket.TCPSendOptions = { 223 data: 'Hello, server!' 224 } 225 sock.send(tcpSendOptions).then(() => { 226 console.log('send success'); 227 }).catch((err: BusinessError) => { 228 console.error('send fail'); 229 }); 230 }) 231} 232 233async function socketTest() { 234 const netConnection = connection.createNetConnection(); 235 netConnection.on('netAvailable', async (netHandle: connection.NetHandle) => { 236 console.log('default network changed'); 237 await sock.close(); 238 sock = socket.constructTCPSocketInstance(); 239 useSocket(); 240 }); 241 try { 242 netConnection.register(() => { 243 }); 244 useSocket(); 245 } catch (e) { 246 console.error(e.code.toString()); 247 } 248} 249``` 250 251#### Original Network Connection Established via Socket Library 252 253Close the original socket and re-establish a socket connection when the default network is changed. 254 255## Obtaining the List of All Registered Networks 256 2571. Declare the required permission: **ohos.permission.GET_NETWORK_INFO**. 258This 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). 259 2602. Import the **connection** namespace from **@kit.NetworkKit**. 261 2623. Call [getAllNets](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetallnets) to obtain the list of all connected networks. 263 264```ts 265// Import the required namespaces. 266import { connection } from '@kit.NetworkKit'; 267import { BusinessError } from '@kit.BasicServicesKit'; 268 269// Construct a singleton object. 270export class GlobalContext { 271 public netList: connection.NetHandle[] = []; 272 private constructor() {} 273 private static instance: GlobalContext; 274 private _objects = new Map<string, Object>(); 275 276 public static getContext(): GlobalContext { 277 if (!GlobalContext.instance) { 278 GlobalContext.instance = new GlobalContext(); 279 } 280 return GlobalContext.instance; 281 } 282 283 getObject(value: string): Object | undefined { 284 return this._objects.get(value); 285 } 286 287 setObject(key: string, objectClass: Object): void { 288 this._objects.set(key, objectClass); 289 } 290} 291 292// Obtain the list of all connected networks. 293connection.getAllNets().then((data: connection.NetHandle[]) => { 294 console.info("Succeeded to get data: " + JSON.stringify(data)); 295 if (data) { 296 GlobalContext.getContext().netList = data; 297 } 298}); 299``` 300 301## Querying Network Capability Information and Connection Information of Specified Data Network 302 3031. Declare the required permission: **ohos.permission.GET_NETWORK_INFO**. 304This 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). 305 3062. Import the **connection** namespace from **@kit.NetworkKit**. 307 3083. Call [getDefaultNet](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetdefaultnet) to obtain the default data network specified by **NetHandle** or call [getAllNets](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetallnets) to obtain the list of all connected networks specified by **Array\<NetHandle>**. 309 3104. Call [getNetCapabilities](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetnetcapabilities) 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. 311 3125. Call [getConnectionProperties](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetconnectionproperties) to obtain the connection information of the data network specified by **NetHandle**. 313 314```ts 315import { connection } from '@kit.NetworkKit'; 316import { BusinessError } from '@kit.BasicServicesKit'; 317 318// Construct a singleton object. 319export class GlobalContext { 320 public netList: connection.NetHandle[] = []; 321 public netHandle: connection.NetHandle|null = null; 322 private constructor() {} 323 private static instance: GlobalContext; 324 private _objects = new Map<string, Object>(); 325 326 public static getContext(): GlobalContext { 327 if (!GlobalContext.instance) { 328 GlobalContext.instance = new GlobalContext(); 329 } 330 return GlobalContext.instance; 331 } 332 333 getObject(value: string): Object | undefined { 334 return this._objects.get(value); 335 } 336 337 setObject(key: string, objectClass: Object): void { 338 this._objects.set(key, objectClass); 339 } 340} 341 342// Call getDefaultNet to obtain the default data network specified by NetHandle. 343connection.getDefaultNet().then((data:connection.NetHandle) => { 344 if (data.netId == 0) { 345 // If the obtained netid of netHandler is 0 when no default network is specified, an exception has occurred and extra processing is needed. 346 return; 347 } 348 if (data) { 349 console.info("getDefaultNet get data: " + JSON.stringify(data)); 350 GlobalContext.getContext().netHandle = data; 351 // 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. 352 connection.getNetCapabilities(GlobalContext.getContext().netHandle).then( 353 (data: connection.NetCapabilities) => { 354 console.info("getNetCapabilities get data: " + JSON.stringify(data)); 355 // Obtain the network type via bearerTypes. 356 let bearerTypes: Set<number> = new Set(data.bearerTypes); 357 let bearerTypesNum = Array.from(bearerTypes.values()); 358 for (let item of bearerTypesNum) { 359 if (item == 0) { 360 // Cellular network 361 console.log(JSON.stringify("BEARER_CELLULAR")); 362 } else if (item == 1) { 363 // Wi-Fi network 364 console.log(JSON.stringify("BEARER_WIFI")); 365 } else if (item == 3) { 366 // Ethernet network 367 console.log(JSON.stringify("BEARER_ETHERNET")); 368 } 369 } 370 371 // Obtain the specific network capabilities via networkCap. 372 let itemNumber : Set<number> = new Set(data.networkCap); 373 let dataNumber = Array.from(itemNumber.values()); 374 for (let item of dataNumber) { 375 if (item == 0) { 376 // The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages. 377 console.log(JSON.stringify("NET_CAPABILITY_MMS")); 378 } else if (item == 11) { 379 // The network traffic is not metered. 380 console.log(JSON.stringify("NET_CAPABILITY_NOT_METERED")); 381 } else if (item == 12) { 382 // The network has the Internet access capability, which is set by the network provider. 383 console.log(JSON.stringify("NET_CAPABILITY_INTERNET")); 384 } else if (item == 15) { 385 // The network does not use a Virtual Private Network (VPN). 386 console.log(JSON.stringify("NET_CAPABILITY_NOT_VPN")); 387 } else if (item == 16) { 388 // The Internet access capability of the network is successfully verified by the connection management module. 389 console.log(JSON.stringify("NET_CAPABILITY_VALIDATED")); 390 } 391 } 392 }) 393 } 394}); 395 396// Obtain the connection information of the data network specified by NetHandle. Connection information includes link and route information. 397connection.getConnectionProperties(GlobalContext.getContext().netHandle).then((data: connection.ConnectionProperties) => { 398 console.info("getConnectionProperties get data: " + JSON.stringify(data)); 399}) 400 401// Call getAllNets to obtain the list of all connected networks specified by Array<NetHandle>. 402connection.getAllNets().then((data: connection.NetHandle[]) => { 403 console.info("getAllNets get data: " + JSON.stringify(data)); 404 if (data) { 405 GlobalContext.getContext().netList = data; 406 407 let itemNumber : Set<connection.NetHandle> = new Set(GlobalContext.getContext().netList); 408 let dataNumber = Array.from(itemNumber.values()); 409 for (let item of dataNumber) { 410 // Obtain the network capability information of the network specified by each netHandle on the network list cyclically. 411 connection.getNetCapabilities(item).then((data: connection.NetCapabilities) => { 412 console.info("getNetCapabilities get data: " + JSON.stringify(data)); 413 }) 414 415 // Obtain the connection information of the network specified by each netHandle on the network list cyclically. 416 connection.getConnectionProperties(item).then((data: connection.ConnectionProperties) => { 417 console.info("getConnectionProperties get data: " + JSON.stringify(data)); 418 }) 419 } 420 } 421}) 422``` 423 424## Resolving the Domain Name of a Network to Obtain All IP Addresses 425 4261. Declare the required permission: **ohos.permission.INTERNET**. 427This 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). 428 4292. Import the **connection** namespace from **@kit.NetworkKit**. 430 4313. Call [getAddressesByName](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetaddressesbyname) to use the default network to resolve the host name to obtain the list of all IP addresses. 432 433```ts 434// Import the required namespaces. 435import { connection } from '@kit.NetworkKit'; 436import { BusinessError } from '@kit.BasicServicesKit'; 437 438// Use the default network to resolve the host name to obtain the list of all IP addresses. 439connection.getAddressesByName("xxxx").then((data: connection.NetAddress[]) => { 440 console.info("Succeeded to get data: " + JSON.stringify(data)); 441}); 442``` 443