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- Default network: network where the default route is located. 18 19## When to Use 20 21Typical application scenarios of network connection management are as follows: 22 23- Subscribing to status changes of the specified network 24- Obtaining the list of all registered networks 25- Querying the connection information of the default network or the specified network 26- Resolving the domain name of the default network to obtain all IP addresses 27 28The following describes the development procedure specific to each application scenario. 29 30## Subscribing to Status Changes of the Specified Network 31 321. Declare the required permission: **ohos.permission.GET_NETWORK_INFO**. 33This 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](../security/AccessToken/declare-permissions.md#declaring-permissions-in-the-configuration-file). 34 352. Import the **connection** namespace from **@kit.NetworkKit**. 36 37 ```ts 38 // Import the required namespaces. 39 import { connection } from '@kit.NetworkKit'; 40 import { BusinessError } from '@kit.BasicServicesKit'; 41 ``` 42 433. 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. 44 45 ```ts 46 let netSpecifier: connection.NetSpecifier = { 47 netCapabilities: { 48 // Assume that the default network is Wi-Fi. If you need to create a cellular network connection, set the network type to CELLULAR. 49 bearerTypes: [connection.NetBearType.BEARER_CELLULAR], 50 // Set the network capability to INTERNET. 51 networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET] 52 }, 53 }; 54 55 // Set the timeout value to 10s. The default value is 0. 56 let timeout = 10 * 1000; 57 58 // Create a NetConnection object. 59 let conn = connection.createNetConnection(netSpecifier, timeout); 60 ``` 61 624. Call [register()](../reference/apis-network-kit/js-apis-net-connection.md#register) to subscribe to network status changes of the specified network. 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. 63 64 ```ts 65 // Register an observer for network status changes. 66 conn.register((err: BusinessError, data: void) => { 67 console.log(JSON.stringify(err)); 68 }); 69 ``` 70 715. Call [on()](../reference/apis-network-kit/js-apis-net-connection.md#onnetavailable) to subscribe to desired events. You must pass in **type** and **callback**. 72 73 ```ts 74 // Subscribe to network status change events. If the network is available, an on_netAvailable event is returned. 75 conn.on('netAvailable', ((data: connection.NetHandle) => { 76 console.log("net is available, netId is " + data.netId); 77 })); 78 79 // Subscribe to network status change events. If the network is unavailable, an on_netUnavailable event is returned. 80 conn.on('netUnavailable', ((data: void) => { 81 console.log("net is unavailable, data is " + JSON.stringify(data)); 82 })); 83 ``` 846. Call [unregister()](../reference/apis-network-kit/js-apis-net-connection.md#unregister) to unsubscribe from the network status changes. 85 86 ```ts 87 // Unregister the observer for network status changes. 88 conn.unregister((err: BusinessError, data: void) => { 89 }); 90 ``` 91 92## Monitoring Changes of the Default Network and Re-establishing the Network Connection 93 94Depending on the current network status and network quality, the default network may change, for example: 951. Switching the default network to the cellular network when the Wi-Fi signal is weak 962. Switching the default network to the Wi-Fi network when the cellular network signal is weak 973. Switching the default network to the cellular network when the Wi-Fi network is disabled 984. Switching the default network to the Wi-Fi network when the cellular network is disabled 995. Switching the default network to another Wi-Fi network when the Wi-Fi signal is weak (cross-network scenario) 1006. Switching the default network to cellular Wi-Fi network when the cellular signal is weak (cross-network scenario) 101 102The following describes how to monitor changes of the default network and migrate application packets to the new default network. 103 104### Monitoring Changes of the Default Network 105 106```ts 107import { connection } from '@kit.NetworkKit'; 108 109async function test() { 110 const netConnection = connection.createNetConnection(); 111 112 /* Listen for changes of the default network */ 113 netConnection.on('netAvailable', (data: connection.NetHandle) => { 114 console.log(JSON.stringify(data)); 115 }); 116} 117``` 118 119### Re-establishing the Network Connection When the Default Network Is Changed 120 121#### Original Network Connection Established via the HTTP Module 122 123If 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. 124 125#### Original Network Connection Established via Remote Communication Kit 126 127```ts 128import { rcp } from '@kit.RemoteCommunicationKit'; 129import { connection } from '@kit.NetworkKit'; 130import { BusinessError } from '@kit.BasicServicesKit'; 131 132let session = rcp.createSession(); 133 134async function useRcp() { 135 // Create an RCP request. // 136 try { 137 const request = await session.get('https://www.example.com'); 138 console.info(request.statusCode.toString()); 139 } catch (e) { 140 console.error(e.code.toString()); 141 } 142} 143 144async function rcpTest() { 145 const netConnection = connection.createNetConnection(); 146 netConnection.on('netAvailable', async (netHandle: connection.NetHandle) => { 147 // Re-establish a session when the default network is changed. 148 session.close(); 149 session = rcp.createSession(); 150 useRcp(); 151 }); 152 try { 153 netConnection.register(() => { 154 }); 155 useRcp(); 156 } catch (e) { 157 console.error(e.code.toString()); 158 } 159} 160``` 161 162#### Original Network Connection Established via the Socket Module 163 164```ts 165import { connection, socket } from '@kit.NetworkKit'; 166import { BusinessError } from '@kit.BasicServicesKit'; 167 168let sock: socket.TCPSocket = socket.constructTCPSocketInstance(); 169 170async function useSocket() { 171 let tcpConnectOptions: socket.TCPConnectOptions = { 172 address: { 173 address: '192.168.xx.xxx', 174 port: 8080 175 }, 176 timeout: 6000 177 } 178 179 /* Set up a socket connection */ 180 sock.connect(tcpConnectOptions, (err: BusinessError) => { 181 if (err) { 182 console.error('connect fail'); 183 return; 184 } 185 console.log('connect success'); 186 187 /* Send data over the socket */ 188 let tcpSendOptions: socket.TCPSendOptions = { 189 data: 'Hello, server!' 190 } 191 sock.send(tcpSendOptions).then(() => { 192 console.log('send success'); 193 }).catch((err: BusinessError) => { 194 console.error('send fail'); 195 }); 196 }) 197} 198 199async function socketTest() { 200 const netConnection = connection.createNetConnection(); 201 netConnection.on('netAvailable', async (netHandle: connection.NetHandle) => { 202 console.log('default network changed'); 203 await sock.close(); 204 sock = socket.constructTCPSocketInstance(); 205 useSocket(); 206 }); 207 try { 208 netConnection.register(() => { 209 }); 210 useSocket(); 211 } catch (e) { 212 console.error(e.code.toString()); 213 } 214} 215``` 216 217#### Original Network Connection Established via Socket Library 218 219Close the original socket and re-establish a socket connection when the default network is changed. 220 221## Obtaining the List of All Registered Networks 222 2231. Declare the required permission: **ohos.permission.GET_NETWORK_INFO**. 224This 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](../security/AccessToken/declare-permissions.md#declaring-permissions-in-the-configuration-file). 225 2262. Import the **connection** namespace from **@kit.NetworkKit**. 227 228 ```ts 229 // Import the required namespaces. 230 import { connection } from '@kit.NetworkKit'; 231 import { BusinessError } from '@kit.BasicServicesKit'; 232 ``` 233 2343. Call [getAllNets](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetallnets) to obtain the list of all connected networks. 235 236 ```ts 237 // Construct a singleton object. 238 export class GlobalContext { 239 public netList: connection.NetHandle[] = []; 240 private constructor() {} 241 private static instance: GlobalContext; 242 private _objects = new Map<string, Object>(); 243 244 public static getContext(): GlobalContext { 245 if (!GlobalContext.instance) { 246 GlobalContext.instance = new GlobalContext(); 247 } 248 return GlobalContext.instance; 249 } 250 251 getObject(value: string): Object | undefined { 252 return this._objects.get(value); 253 } 254 255 setObject(key: string, objectClass: Object): void { 256 this._objects.set(key, objectClass); 257 } 258 } 259 260 // Obtain the list of all connected networks. 261 connection.getAllNets().then((data: connection.NetHandle[]) => { 262 console.info("Succeeded to get data: " + JSON.stringify(data)); 263 if (data) { 264 GlobalContext.getContext().netList = data; 265 } 266 }); 267 ``` 268 269## Querying the Connection Information of the Default Network or the Specified Network 270 2711. Declare the required permission: **ohos.permission.GET_NETWORK_INFO**. 272This 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](../security/AccessToken/declare-permissions.md#declaring-permissions-in-the-configuration-file). 273 2742. Import the **connection** namespace from **@kit.NetworkKit**. 275 276 ```ts 277 import { connection } from '@kit.NetworkKit'; 278 import { BusinessError } from '@kit.BasicServicesKit'; 279 ``` 280 2813. Call [getDefaultNet](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetdefaultnet) to obtain the default data network identified by **NetHandle** and call [getNetCapabilities](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetnetcapabilities) to obtain its network capability information. The capability information includes information such as the network type (cellular, Wi-Fi, or Ethernet network) and the specific network capabilities. Alternatively, you can call [getConnectionProperties](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetconnectionproperties) to obtain the connection information of the data network specified by **NetHandle**. 282 283 ```ts 284 // Construct a singleton object. 285 export class GlobalContext { 286 public netList: connection.NetHandle[] = []; 287 public netHandle: connection.NetHandle|null = null; 288 private constructor() {} 289 private static instance: GlobalContext; 290 private _objects = new Map<string, Object>(); 291 292 public static getContext(): GlobalContext { 293 if (!GlobalContext.instance) { 294 GlobalContext.instance = new GlobalContext(); 295 } 296 return GlobalContext.instance; 297 } 298 299 getObject(value: string): Object | undefined { 300 return this._objects.get(value); 301 } 302 303 setObject(key: string, objectClass: Object): void { 304 this._objects.set(key, objectClass); 305 } 306 } 307 308 // Call getDefaultNet to obtain the default data network specified by NetHandle. 309 connection.getDefaultNet().then((data:connection.NetHandle) => { 310 if (data.netId == 0) { 311 // If the obtained netid of netHandler is 0 when no default network is specified, an exception has occurred and extra processing is needed. 312 return; 313 } 314 if (data) { 315 console.info("getDefaultNet get data: " + JSON.stringify(data)); 316 GlobalContext.getContext().netHandle = data; 317 // 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. 318 connection.getNetCapabilities(GlobalContext.getContext().netHandle).then( 319 (data: connection.NetCapabilities) => { 320 console.info("getNetCapabilities get data: " + JSON.stringify(data)); 321 // Obtain the network type via bearerTypes. 322 let bearerTypes: Set<number> = new Set(data.bearerTypes); 323 let bearerTypesNum = Array.from(bearerTypes.values()); 324 for (let item of bearerTypesNum) { 325 if (item == 0) { 326 // Cellular network 327 console.log(JSON.stringify("BEARER_CELLULAR")); 328 } else if (item == 1) { 329 // Wi-Fi network 330 console.log(JSON.stringify("BEARER_WIFI")); 331 } else if (item == 3) { 332 // Ethernet network 333 console.log(JSON.stringify("BEARER_ETHERNET")); 334 } 335 } 336 337 // Obtain the specific network capabilities via networkCap. 338 let itemNumber : Set<number> = new Set(data.networkCap); 339 let dataNumber = Array.from(itemNumber.values()); 340 for (let item of dataNumber) { 341 if (item == 0) { 342 // The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages. 343 console.log(JSON.stringify("NET_CAPABILITY_MMS")); 344 } else if (item == 11) { 345 // The network traffic is not metered. 346 console.log(JSON.stringify("NET_CAPABILITY_NOT_METERED")); 347 } else if (item == 12) { 348 // The network has the Internet access capability, which is set by the network provider. 349 console.log(JSON.stringify("NET_CAPABILITY_INTERNET")); 350 } else if (item == 15) { 351 // The network does not use a Virtual Private Network (VPN). 352 console.log(JSON.stringify("NET_CAPABILITY_NOT_VPN")); 353 } else if (item == 16) { 354 // The Internet access capability of the network is successfully verified by the connection management module. 355 console.log(JSON.stringify("NET_CAPABILITY_VALIDATED")); 356 } 357 } 358 }) 359 } 360 }); 361 362 // Obtain the connection information of the data network specified by NetHandle. Connection information includes link and route information. 363 connection.getConnectionProperties(GlobalContext.getContext().netHandle).then((data: connection.ConnectionProperties) => { 364 console.info("getConnectionProperties get data: " + JSON.stringify(data)); 365 }) 366 ``` 367 3684. Alternatively, call [getAllNets](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetallnets) to obtain the list of all connected networks specified by **Array\<NetHandle>**. Then, traverse the obtained **NetHandle** array and call [getNetCapabilities](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetnetcapabilities) to obtain the capability information of the network identified by each **NetHandle**. The capability information includes the network type (cellular network, Wi-Fi network, or Ethernet network) and network capability. Alternatively, you can call [getConnectionProperties](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetconnectionproperties) to obtain the connection information of the data network specified by **NetHandle**. 369 370 ```ts 371 // Call getAllNets to obtain the list of all connected networks specified by Array<NetHandle>. 372 connection.getAllNets().then((data: connection.NetHandle[]) => { 373 console.info("getAllNets get data: " + JSON.stringify(data)); 374 if (data) { 375 GlobalContext.getContext().netList = data; 376 377 let itemNumber : Set<connection.NetHandle> = new Set(GlobalContext.getContext().netList); 378 let dataNumber = Array.from(itemNumber.values()); 379 for (let item of dataNumber) { 380 // Obtain the network capability information of the network specified by each netHandle on the network list cyclically. 381 connection.getNetCapabilities(item).then((data: connection.NetCapabilities) => { 382 console.info("getNetCapabilities get data: " + JSON.stringify(data)); 383 }) 384 385 // Obtain the connection information of the network specified by each netHandle on the network list cyclically. 386 connection.getConnectionProperties(item).then((data: connection.ConnectionProperties) => { 387 console.info("getConnectionProperties get data: " + JSON.stringify(data)); 388 }) 389 } 390 } 391 }) 392 ``` 393 394## Checking Whether the Default Network Supports Internet Access 395 396If an application needs to check whether the current network supports Internet access, perform the following steps: 397 3981. Declare the required permission: **ohos.permission.GET_NETWORK_INFO**. 399This 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](../security/AccessToken/declare-permissions.md#declaring-permissions-in-the-configuration-file). 400 4012. Import the **connection** namespace from **@kit.NetworkKit**. 402 403 ```ts 404 // Import the required namespaces. 405 import { connection } from '@kit.NetworkKit'; 406 import { BusinessError } from '@kit.BasicServicesKit'; 407 ``` 408 4093. Call he [getDefaultNetSync](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetdefaultnetsync9) to obtain **netHandle** of the default network. If **netHandle** is valid, call [getNetCapabilitiesSync](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetnetcapabilitiessync10) to obtain the capability information of the corresponding network and determine whether Internet access is supported. 410 411 ```ts 412 judgeHasNet(): boolean { 413 try { 414 let netHandle = connection.getDefaultNetSync(); 415 if (!netHandle || netHandle.netId === 0) { 416 return false; 417 } 418 let netCapabilities = connection.getNetCapabilitiesSync(netHandle); 419 let cap = netCapabilities.networkCap || []; 420 if (!cap.includes(connection.NetCap.NET_CAPABILITY_CHECKING_CONNECTIVITY) && cap.includes(connection.NetCap.NET_CAPABILITY_VALIDATED)) { 421 // NET_CAPABILITY_CHECKING_CONNECTIVITY indicates that a network connectivity check is in progress. The network connectivity verification is successful if the network connectivity check is complete and NET_CAPABILITY_VALIDATED is contained in networkCap. 422 return true; 423 } else { 424 return false; 425 } 426 } catch (e) { 427 let err = e as BusinessError; 428 console.error("judgeHasNet error" + JSON.stringify(err)); 429 } 430 return false; 431 } 432 ``` 433 434## Resolving the Domain Name of the Default Network to Obtain All IP Addresses 435 4361. Declare the required permission: **ohos.permission.GET_NETWORK_INFO**. 437This 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](../security/AccessToken/declare-permissions.md#declaring-permissions-in-the-configuration-file). 438 4392. Import the **connection** namespace from **@kit.NetworkKit**. 440 441 ```ts 442 // Import the required namespaces. 443 import { connection } from '@kit.NetworkKit'; 444 import { BusinessError } from '@kit.BasicServicesKit'; 445 ``` 446 447 3. 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. 448 449 ```ts 450 // Use the default network to resolve the host name to obtain the list of all IP addresses. 451 connection.getAddressesByName("xxxx").then((data: connection.NetAddress[]) => { 452 console.info("Succeeded to get data: " + JSON.stringify(data)); 453 }); 454 ``` 455