1# @ohos.net.connection (Network Connection Management) 2 3<!--Kit: Network Kit--> 4<!--Subsystem: Communication--> 5<!--Owner: @wmyao_mm--> 6<!--Designer: @guo-min_net--> 7<!--Tester: @tongxilin--> 8<!--Adviser: @zhang_yixin13--> 9 10The **connection** module provides basic network management capabilities. With the APIs provided by this module, you can obtain the default active data network or the list of all active data networks, enable or disable the airplane mode, and obtain network capability information. 11 12> **NOTE** 13> 14> 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. 15> 16> Unless otherwise specified, the APIs of this module do not support concurrent calls. 17 18## Modules to Import 19 20```ts 21import { connection } from '@kit.NetworkKit'; 22``` 23 24## connection.createNetConnection 25 26createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection 27 28Creates a **NetConnection** object, where [netSpecifier](#netspecifier) specifies the network, and **timeout** specifies the timeout duration in ms. **timeout** is configurable only when **netSpecifier** is specified. If neither of them is present, the default network is used. 29 30**Note**: **createNetConnection** supports up to 2,000 registered callbacks. Exceeding this limit will result in a registration failure. 31 32**Atomic service API**: This API can be used in atomic services since API version 11. 33 34**System capability**: SystemCapability.Communication.NetManager.Core 35 36**Parameters** 37 38| Name | Type | Mandatory| Description | 39| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | 40| netSpecifier | [NetSpecifier](#netspecifier) | No | Network specifier, which specifies the network capability. If this parameter is left unspecified, the default network is used. | 41| timeout | number | No | Timeout interval for obtaining the network specified by **netSpecifier**. The input value must be an uint32_t integer. This parameter is valid only when **netSpecifier** is present. The default value is **0**.| 42 43**Return value** 44 45| Type | Description | 46| ------------------------------- | -------------------- | 47| [NetConnection](#netconnection) | Handle of the network specified by **netSpecifier**.| 48 49**Example** 50 51```ts 52import { connection } from '@kit.NetworkKit'; 53 54// Use the default network. No parameter needs to be passed. 55let netConnection = connection.createNetConnection(); 56 57// Use the cellular network. Pass in network capabilities as needed. If the timeout parameter is not present, the value is 0, which indicates no timeout limit. 58let netConnectionCellular = connection.createNetConnection({ 59 netCapabilities: { 60 bearerTypes: [connection.NetBearType.BEARER_CELLULAR] 61 } 62}); 63``` 64 65## connection.getDefaultNet 66 67getDefaultNet(callback: AsyncCallback\<NetHandle>): void 68 69Obtains the default active data network. This API uses an asynchronous callback to return the result. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities. 70 71**Required permission**: ohos.permission.GET_NETWORK_INFO 72 73**Atomic service API**: This API can be used in atomic services since API version 11. 74 75**System capability**: SystemCapability.Communication.NetManager.Core 76 77**Parameters** 78 79| Name | Type | Mandatory| Description | 80| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | 81| callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. If the default activated data network is obtained successfully, **error** is **undefined** and **data** is the default activated data network. Otherwise, **error** is an error object.| 82 83**Error codes** 84 85For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 86 87| ID| Error Message | 88| ------- | ----------------------------- | 89| 201 | Permission denied. | 90| 401 | Parameter error. | 91| 2100002 | Failed to connect to the service. | 92| 2100003 | System internal error. | 93 94**Example** 95 96```ts 97import { connection } from '@kit.NetworkKit'; 98import { BusinessError } from '@kit.BasicServicesKit'; 99 100connection.getDefaultNet((error: BusinessError, data: connection.NetHandle) => { 101 if (error) { 102 console.error(`Failed to get default net. Code:${error.code}, message:${error.message}`); 103 return; 104 } 105 console.info("Succeeded to get data " + JSON.stringify(data)); 106}); 107``` 108 109## connection.getDefaultNet 110 111getDefaultNet(): Promise\<NetHandle> 112 113Obtains the default active data network. This API uses a promise to return the result. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities. 114 115**Required permission**: ohos.permission.GET_NETWORK_INFO 116 117**Atomic service API**: This API can be used in atomic services since API version 11. 118 119**System capability**: SystemCapability.Communication.NetManager.Core 120 121**Return value** 122 123| Type | Description | 124| --------------------------------- | ------------------------------------- | 125| Promise\<[NetHandle](#nethandle)> | Promise used to return the result.| 126 127**Error codes** 128 129For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 130 131| ID| Error Message | 132| ------- | -------------------------------- | 133| 201 | Permission denied. | 134| 2100002 | Failed to connect to the service.| 135| 2100003 | System internal error. | 136 137**Example** 138 139```ts 140import { connection } from '@kit.NetworkKit'; 141 142connection.getDefaultNet().then((data: connection.NetHandle) => { 143 console.info("Succeeded to get data: " + JSON.stringify(data)); 144}); 145``` 146 147## connection.getDefaultNetSync<sup>9+</sup> 148 149getDefaultNetSync(): NetHandle 150 151Obtains the default active data network in synchronous mode. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities. 152 153**Required permission**: ohos.permission.GET_NETWORK_INFO 154 155**Atomic service API**: This API can be used in atomic services since API version 11. 156 157**System capability**: SystemCapability.Communication.NetManager.Core 158 159**Return value** 160 161| Type | Description | 162| --------- | ---------------------------------- | 163| [NetHandle](#nethandle) | Handle of the default active data network.| 164 165**Error codes** 166 167For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 168 169| ID| Error Message | 170| ------- | -------------------------------- | 171| 201 | Permission denied. | 172| 2100002 | Failed to connect to the service.| 173| 2100003 | System internal error. | 174 175**Example** 176 177```ts 178import { connection } from '@kit.NetworkKit'; 179 180let netHandle = connection.getDefaultNetSync(); 181``` 182 183 184## connection.setAppHttpProxy<sup>11+</sup> 185 186setAppHttpProxy(httpProxy: HttpProxy): void 187 188Sets the application-level HTTP proxy configuration. 189 190**System capability**: SystemCapability.Communication.NetManager.Core 191 192**Parameters** 193 194| Name | Type | Mandatory| Description | 195| --------- | ------------------------------------------------------------ | ---- | ---------------- | 196| httpProxy | [HttpProxy](#httpproxy10) | Yes | Application-level HTTP proxy configuration.| 197 198**Error codes** 199 200For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 201 202| ID| Error Message | 203| ------- | ----------------------------- | 204| 401 | Parameter error. | 205| 2100001 | Invalid http proxy. | 206 207**Example** 208 209```ts 210import { connection } from '@kit.NetworkKit'; 211import { BusinessError } from '@kit.BasicServicesKit'; 212 213let exclusionStr = "192.168,baidu.com"; 214let exclusionArray = exclusionStr.split(','); 215connection.setAppHttpProxy({ 216 host: "192.168.xx.xxx", 217 port: 8080, 218 exclusionList: exclusionArray 219} as connection.HttpProxy); 220``` 221 222## connection.getDefaultHttpProxy<sup>10+</sup> 223 224getDefaultHttpProxy(callback: AsyncCallback\<HttpProxy>): void 225 226Obtains the default HTTP proxy configuration of the network. If the global proxy is set, the global HTTP proxy configuration is returned. If [setAppNet](#connectionsetappnet9) is used to bind the application to the network specified by [NetHandle](#nethandle), the HTTP proxy configuration of this network is returned. In other cases, the HTTP proxy configuration of the default network is returned. This API uses an asynchronous callback to return the result. 227 228**System capability**: SystemCapability.Communication.NetManager.Core 229 230**Parameters** 231 232| Name | Type | Mandatory| Description | 233| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | 234| callback | AsyncCallback<[HttpProxy](#httpproxy10)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.| 235 236**Error codes** 237 238For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md). 239 240| ID| Error Message | 241| -------- | -------------------------------------------- | 242| 2100002 | Failed to connect to the service. | 243| 2100003 | System internal error. | 244 245**Example** 246 247```ts 248import { connection } from '@kit.NetworkKit'; 249import { BusinessError } from '@kit.BasicServicesKit'; 250 251connection.getDefaultHttpProxy((error: BusinessError, data: connection.HttpProxy) => { 252 if (error) { 253 console.error(`Failed to get default http proxy. Code:${error.code}, message:${error.message}`); 254 return; 255 } 256 console.log("Succeeded to get data" + JSON.stringify(data)); 257}); 258``` 259 260## connection.getDefaultHttpProxy<sup>10+</sup> 261 262getDefaultHttpProxy(): Promise\<HttpProxy> 263 264Obtains the default HTTP proxy configuration of the network. If the global proxy is set, the global HTTP proxy configuration is returned. If [setAppNet](#connectionsetappnet9) is used to bind the application to the network specified by [NetHandle](#nethandle), the HTTP proxy configuration of this network is returned. In other cases, the HTTP proxy configuration of the default network is returned. This API uses a promise to return the result. 265 266**System capability**: SystemCapability.Communication.NetManager.Core 267 268**Return value** 269 270| Type | Description | 271| -------------------------------- | ----------------------------------------- | 272| Promise<[HttpProxy](#httpproxy10)> | Promise used to return the result.| 273 274**Error codes** 275 276For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md). 277 278| ID| Error Message | 279| -------- | -------------------------------------------- | 280| 2100002 | Failed to connect to the service. | 281| 2100003 | System internal error. | 282 283**Example** 284 285```ts 286import { connection } from '@kit.NetworkKit'; 287import { BusinessError } from '@kit.BasicServicesKit'; 288 289connection.getDefaultHttpProxy().then((data: connection.HttpProxy) => { 290 console.info(JSON.stringify(data)); 291}).catch((error: BusinessError) => { 292 console.info(JSON.stringify(error)); 293}); 294``` 295 296## connection.getAppNet<sup>9+</sup> 297 298getAppNet(callback: AsyncCallback\<NetHandle>): void 299 300Obtains information about the network bound to an application. This API uses an asynchronous callback to return the result. 301 302**System capability**: SystemCapability.Communication.NetManager.Core 303 304**Parameters** 305 306| Name | Type | Mandatory| Description | 307| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | 308| callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. If information about the network bound to the application is successfully obtained, **error** is **undefined** and **data** is the obtained network information. Otherwise, **error** is an error object.| 309 310**Error codes** 311 312For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 313 314| ID| Error Message | 315| ------- | ----------------------------- | 316| 401 | Parameter error. | 317| 2100002 | Failed to connect to the service.| 318| 2100003 | System internal error. | 319 320**Example** 321 322```ts 323import { connection } from '@kit.NetworkKit'; 324import { BusinessError } from '@kit.BasicServicesKit'; 325 326connection.getAppNet((error: BusinessError, data: connection.NetHandle) => { 327 if (error) { 328 console.error(`Failed to get App net. Code:${error.code}, message:${error.message}`); 329 return; 330 } 331 console.info("Succeeded to get data: " + JSON.stringify(data)); 332}) 333``` 334 335## connection.getAppNet<sup>9+</sup> 336 337getAppNet(): Promise\<NetHandle> 338 339Obtains information about the network bound to an application. This API uses a promise to return the result. 340 341**System capability**: SystemCapability.Communication.NetManager.Core 342 343**Return value** 344 345| Type | Description | 346| --------------------------------- | ------------------------------------- | 347| Promise\<[NetHandle](#nethandle)> | Promise used to return the result.| 348 349**Error codes** 350 351For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md). 352 353| ID| Error Message | 354| ------- | ----------------------------- | 355| 2100002 | Failed to connect to the service.| 356| 2100003 | System internal error. | 357 358**Example** 359 360```ts 361import { connection } from '@kit.NetworkKit'; 362import { BusinessError } from '@kit.BasicServicesKit'; 363 364connection.getAppNet().then((data: connection.NetHandle) => { 365 console.info(JSON.stringify(data)); 366}).catch((error: BusinessError) => { 367 console.info(JSON.stringify(error)); 368}); 369``` 370 371## connection.getAppNetSync<sup>10+</sup> 372 373getAppNetSync(): NetHandle 374 375Obtains information about the network bound to an application. This API returns the result synchronously. 376 377**System capability**: SystemCapability.Communication.NetManager.Core 378 379**Return value** 380 381| Type | Description | 382| --------- | ---------------------------------- | 383| [NetHandle](#nethandle) | Data network bound to the application.| 384 385**Error codes** 386 387For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md). 388 389| ID| Error Message | 390| ------- | ----------------------------- | 391| 2100002 | Failed to connect to the service.| 392| 2100003 | System internal error. | 393 394**Example** 395 396```ts 397import { connection } from '@kit.NetworkKit'; 398 399let netHandle = connection.getAppNetSync(); 400``` 401 402## connection.setAppNet<sup>9+</sup> 403 404setAppNet(netHandle: NetHandle, callback: AsyncCallback\<void>): void 405 406Binds an application to the network specified by **netHandle**, so that the application can access the external network only through this network, so that the application can access the external network only through this network. This API uses an asynchronous callback to return the result. 407 408**Required permissions**: ohos.permission.INTERNET 409 410**System capability**: SystemCapability.Communication.NetManager.Core 411 412**Parameters** 413 414| Name | Type | Mandatory| Description | 415| --------- | ----------------------- | ---- | ------------------------------------------------------------ | 416| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network. | 417| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the application is successfully bound to the specified network, **error** is **undefined**. Otherwise, **error** is an error object.| 418 419**Error codes** 420 421For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 422 423| ID| Error Message | 424| ------- | ----------------------------- | 425| 201 | Permission denied. | 426| 401 | Parameter error. | 427| 2100001 | Invalid parameter value. | 428| 2100002 | Failed to connect to the service.| 429| 2100003 | System internal error. | 430 431**Example** 432 433```ts 434import { connection } from '@kit.NetworkKit'; 435import { BusinessError } from '@kit.BasicServicesKit'; 436 437connection.getDefaultNet((error: BusinessError, netHandle: connection.NetHandle) => { 438 if (netHandle.netId == 0) { 439 // If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements. 440 return; 441 } 442 connection.setAppNet(netHandle, (error: BusinessError, data: void) => { 443 if (error) { 444 console.error(`Failed to get default net. Code:${error.code}, message:${error.message}`); 445 return; 446 } 447 console.info("Succeeded to get data: " + JSON.stringify(data)); 448 }); 449}); 450``` 451 452## connection.setAppNet<sup>9+</sup> 453 454setAppNet(netHandle: NetHandle): Promise\<void\> 455 456Binds an application to the network specified by **netHandle**, so that the application can access the external network only through this network. This API uses a promise to return the result. This API uses a promise to return the result. 457 458**Required permissions**: ohos.permission.INTERNET 459 460**System capability**: SystemCapability.Communication.NetManager.Core 461 462**Parameters** 463 464| Name | Type | Mandatory| Description | 465| --------- | ------------------------------------------------------------ | ---- | ---------------- | 466| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| 467 468**Return value** 469 470| Type | Description | 471| ------------------------------------------- | ----------------------------- | 472| Promise\<void\> | Promise that returns no value.| 473 474**Error codes** 475 476For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 477 478| ID| Error Message | 479| ------- | ----------------------------- | 480| 201 | Permission denied. | 481| 401 | Parameter error. | 482| 2100001 | Invalid parameter value. | 483| 2100002 | Failed to connect to the service.| 484| 2100003 | System internal error. | 485 486**Example** 487 488```ts 489import { connection } from '@kit.NetworkKit'; 490import { BusinessError } from '@kit.BasicServicesKit'; 491 492connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 493 if (netHandle.netId == 0) { 494 // If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements. 495 return; 496 } 497 498 connection.setAppNet(netHandle).then(() => { 499 console.log("success"); 500 }).catch((error: BusinessError) => { 501 console.error(JSON.stringify(error)); 502 }) 503}); 504``` 505 506## connection.getAllNets 507 508getAllNets(callback: AsyncCallback<Array<NetHandle>>): void 509 510Obtains the list of all connected networks. This API uses an asynchronous callback to return the result. 511 512**Required permission**: ohos.permission.GET_NETWORK_INFO 513 514**System capability**: SystemCapability.Communication.NetManager.Core 515 516**Parameters** 517 518| Name| Type| Mandatory| Description| 519| -------- | -------- | -------- | -------- | 520| callback | AsyncCallback<Array<[NetHandle](#nethandle)>> | Yes| Callback used to return the result. If the list of all connected networks is obtained successfully, **error** is **undefined** and **data** is the list of activated data networks. Otherwise, **error** is an error object.| 521 522**Error codes** 523 524For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 525 526| ID| Error Message | 527| ------- | ----------------------------- | 528| 201 | Permission denied. | 529| 401 | Parameter error. | 530| 2100002 | Failed to connect to the service.| 531| 2100003 | System internal error. | 532 533**Example** 534 535```ts 536import { connection } from '@kit.NetworkKit'; 537import { BusinessError } from '@kit.BasicServicesKit'; 538 539connection.getAllNets((error: BusinessError, data: connection.NetHandle[]) => { 540 if (error) { 541 console.error(`Failed to get all nets. Code:${error.code}, message:${error.message}`); 542 return; 543 } 544 console.info("Succeeded to get data: " + JSON.stringify(data)); 545}); 546``` 547 548## connection.getAllNets 549 550getAllNets(): Promise<Array<NetHandle>> 551 552Obtains the list of all connected networks. This API uses a promise to return the result. 553 554**Required permission**: ohos.permission.GET_NETWORK_INFO 555 556**System capability**: SystemCapability.Communication.NetManager.Core 557 558**Return value** 559 560| Type| Description| 561| -------- | -------- | 562| Promise<Array<[NetHandle](#nethandle)>> | Promise used to return the result.| 563 564**Error codes** 565 566For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 567 568| ID| Error Message | 569| ------- | ----------------------------- | 570| 201 | Permission denied. | 571| 2100002 | Failed to connect to the service.| 572| 2100003 | System internal error. | 573 574**Example** 575 576```ts 577import { connection } from '@kit.NetworkKit'; 578 579connection.getAllNets().then((data: connection.NetHandle[]) => { 580 console.info("Succeeded to get data: " + JSON.stringify(data)); 581}); 582``` 583 584## connection.getAllNetsSync<sup>10+</sup> 585 586getAllNetsSync(): Array<NetHandle> 587 588Obtains the list of all connected networks. This API returns the result synchronously. 589 590**Required permission**: ohos.permission.GET_NETWORK_INFO 591 592**System capability**: SystemCapability.Communication.NetManager.Core 593 594**Return value** 595 596| Type | Description | 597| --------- | ---------------------------------- | 598| Array<[NetHandle](#nethandle)> | List of all connected data networks.| 599 600**Error codes** 601 602For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 603 604| ID| Error Message | 605| ------- | ----------------------------- | 606| 201 | Permission denied. | 607| 2100002 | Failed to connect to the service.| 608| 2100003 | System internal error. | 609 610**Example** 611 612```ts 613import { connection } from '@kit.NetworkKit'; 614 615let netHandle = connection.getAllNetsSync(); 616``` 617 618## connection.getConnectionProperties 619 620getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<ConnectionProperties>): void 621 622Obtains connection properties of the network specified by **netHandle**. This API uses an asynchronous callback to return the result. 623 624**Required permission**: ohos.permission.GET_NETWORK_INFO 625 626**System capability**: SystemCapability.Communication.NetManager.Core 627 628**Parameters** 629 630| Name | Type | Mandatory| Description | 631| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 632| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network. | 633| callback | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | Yes | Callback used to return the result. If the connection properties of the network specified by **netHandle** is obtained successfully, **error** is **undefined** and **data** is the obtained network connection information. Otherwise, **error** is an error object.| 634 635**Error codes** 636 637For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 638 639| ID| Error Message | 640| ------- | ----------------------------- | 641| 201 | Permission denied. | 642| 401 | Parameter error. | 643| 2100001 | Invalid parameter value. | 644| 2100002 | Failed to connect to the service.| 645| 2100003 | System internal error. | 646 647**Example** 648 649```ts 650import { connection } from '@kit.NetworkKit'; 651import { BusinessError } from '@kit.BasicServicesKit'; 652 653connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 654 if (netHandle.netId == 0) { 655 // If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements. 656 return; 657 } 658 connection.getConnectionProperties(netHandle, (error: BusinessError, data: connection.ConnectionProperties) => { 659 if (error) { 660 console.error(`Failed to get connection properties. Code:${error.code}, message:${error.message}`); 661 return; 662 } 663 console.info("Succeeded to get data: " + JSON.stringify(data)); 664 }) 665}); 666``` 667 668## connection.getConnectionProperties 669 670getConnectionProperties(netHandle: NetHandle): Promise\<ConnectionProperties> 671 672Obtains connection properties of the network specified by **netHandle**. This API uses a promise to return the result. 673 674**Required permission**: ohos.permission.GET_NETWORK_INFO 675 676**System capability**: SystemCapability.Communication.NetManager.Core 677 678**Parameters** 679 680| Name | Type | Mandatory| Description | 681| --------- | ----------------------- | ---- | ---------------- | 682| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| 683 684**Return value** 685 686| Type | Description | 687| ------------------------------------------------------- | --------------------------------- | 688| Promise\<[ConnectionProperties](#connectionproperties)> | Promise used to return the result.| 689 690**Error codes** 691 692For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 693 694| ID| Error Message | 695| ------- | ----------------------------- | 696| 201 | Permission denied. | 697| 401 | Parameter error. | 698| 2100001 | Invalid parameter value. | 699| 2100002 | Failed to connect to the service.| 700| 2100003 | System internal error. | 701 702**Example** 703 704```ts 705import { connection } from '@kit.NetworkKit'; 706 707connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 708 if (netHandle.netId == 0) { 709 // If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements. 710 return; 711 } 712 713 connection.getConnectionProperties(netHandle).then((data: connection.ConnectionProperties) => { 714 console.info("Succeeded to get data: " + JSON.stringify(data)); 715 }) 716}); 717``` 718 719## connection.getConnectionPropertiesSync<sup>10+</sup> 720 721getConnectionPropertiesSync(netHandle: NetHandle): ConnectionProperties 722 723Obtains network connection information based on the specified **netHandle**. 724 725**Required permission**: ohos.permission.GET_NETWORK_INFO 726 727**System capability**: SystemCapability.Communication.NetManager.Core 728 729**Parameters** 730 731| Name | Type | Mandatory| Description | 732| --------- | ----------------------- | ---- | ---------------- | 733| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| 734 735**Return value** 736 737| Type | Description | 738| ------------------------------------------------------- | --------------------------------- | 739| [ConnectionProperties](#connectionproperties) | Network connection information.| 740 741**Error codes** 742 743For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 744 745| ID| Error Message | 746| ------- | ----------------------------- | 747| 201 | Permission denied. | 748| 401 | Parameter error. | 749| 2100001 | Invalid parameter value. | 750| 2100002 | Failed to connect to the service.| 751| 2100003 | System internal error. | 752 753**Example** 754 755```ts 756import { connection } from '@kit.NetworkKit'; 757import { BusinessError } from '@kit.BasicServicesKit'; 758 759let netHandle: connection.NetHandle; 760let connectionproperties: connection.ConnectionProperties; 761 762connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 763 if (netHandle.netId == 0) { 764 // If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements. 765 return; 766 } 767 netHandle = connection.getDefaultNetSync(); 768 connectionproperties = connection.getConnectionPropertiesSync(netHandle); 769 console.info("Succeeded to get connectionproperties: " + JSON.stringify(connectionproperties)); 770}); 771 772``` 773 774## connection.getNetCapabilities 775 776getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilities>): void 777 778Obtains capability information of the network specified by **netHandle**. This API uses an asynchronous callback to return the result. 779 780**Required permission**: ohos.permission.GET_NETWORK_INFO 781 782**Atomic service API**: This API can be used in atomic services since API version 11. 783 784**System capability**: SystemCapability.Communication.NetManager.Core 785 786**Parameters** 787 788| Name | Type | Mandatory| Description | 789| --------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | 790| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network. | 791| callback | AsyncCallback\<[NetCapabilities](#netcapabilities)> | Yes | Callback used to return the result. If the capability information of the network specified by **netHandle** is obtained successfully, **error** is **undefined** and **data** is the obtained network capability information. Otherwise, **error** is an error object.| 792 793**Error codes** 794 795For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 796 797| ID| Error Message | 798| ------- | ----------------------------- | 799| 201 | Permission denied. | 800| 401 | Parameter error. | 801| 2100001 | Invalid parameter value. | 802| 2100002 | Failed to connect to the service.| 803| 2100003 | System internal error. | 804 805**Example** 806 807```ts 808import { connection } from '@kit.NetworkKit'; 809import { BusinessError } from '@kit.BasicServicesKit'; 810 811connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 812 if (netHandle.netId == 0) { 813 // If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements. 814 return; 815 } 816 connection.getNetCapabilities(netHandle, (error: BusinessError, data: connection.NetCapabilities) => { 817 if (error) { 818 console.error(`Failed to get net capabilities. Code:${error.code}, message:${error.message}`); 819 return; 820 } 821 console.info("Succeeded to get data: " + JSON.stringify(data)); 822 }) 823}).catch((error: BusinessError) => { 824 console.error(JSON.stringify(error)); 825}); 826``` 827 828## connection.getNetCapabilities 829 830getNetCapabilities(netHandle: NetHandle): Promise\<NetCapabilities> 831 832Obtains capability information of the network specified by **netHandle**. This API uses a promise to return the result. 833 834**Required permission**: ohos.permission.GET_NETWORK_INFO 835 836**Atomic service API**: This API can be used in atomic services since API version 11. 837 838**System capability**: SystemCapability.Communication.NetManager.Core 839 840**Parameters** 841 842| Name | Type | Mandatory| Description | 843| --------- | ----------------------- | ---- | ---------------- | 844| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| 845 846**Return value** 847 848| Type | Description | 849| --------------------------------------------- | --------------------------------- | 850| Promise\<[NetCapabilities](#netcapabilities)> | Promise used to return the result.| 851 852**Error codes** 853 854For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 855 856| ID| Error Message | 857| ------- | ----------------------------- | 858| 201 | Permission denied. | 859| 401 | Parameter error. | 860| 2100001 | Invalid parameter value. | 861| 2100002 | Failed to connect to the service.| 862| 2100003 | System internal error. | 863 864**Example** 865 866```ts 867import { connection } from '@kit.NetworkKit'; 868 869connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 870 if (netHandle.netId == 0) { 871 // If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements. 872 return; 873 } 874 connection.getNetCapabilities(netHandle).then((data: connection.NetCapabilities) => { 875 console.info("Succeeded to get data: " + JSON.stringify(data)); 876 }) 877}).catch((error: BusinessError) => { 878 console.error(JSON.stringify(error)); 879}); 880``` 881 882## connection.getNetCapabilitiesSync<sup>10+</sup> 883 884getNetCapabilitiesSync(netHandle: NetHandle): NetCapabilities 885 886Obtains capability information of the network specified by **netHandle**. This API returns the result synchronously. 887 888**Required permission**: ohos.permission.GET_NETWORK_INFO 889 890**Atomic service API**: This API can be used in atomic services since API version 11. 891 892**System capability**: SystemCapability.Communication.NetManager.Core 893 894**Parameters** 895 896| Name | Type | Mandatory| Description | 897| --------- | ----------------------- | ---- | ---------------- | 898| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| 899 900**Return value** 901 902| Type | Description | 903| --------------------------------------------- | --------------------------------- | 904| [NetCapabilities](#netcapabilities) | Network capability information.| 905 906**Error codes** 907 908For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 909 910| ID| Error Message | 911| ------- | ----------------------------- | 912| 201 | Permission denied. | 913| 401 | Parameter error. | 914| 2100001 | Invalid parameter value. | 915| 2100002 | Failed to connect to the service.| 916| 2100003 | System internal error. | 917 918**Example** 919 920```ts 921import { connection } from '@kit.NetworkKit'; 922import { BusinessError } from '@kit.BasicServicesKit'; 923 924let netHandle: connection.NetHandle; 925let getNetCapabilitiesSync: connection.NetCapabilities; 926 927connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 928 if (netHandle.netId == 0) { 929 // If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements. 930 return; 931 } 932 933 getNetCapabilitiesSync = connection.getNetCapabilitiesSync(netHandle); 934 console.info("Succeeded to get net capabilities sync: " + JSON.stringify(getNetCapabilitiesSync)); 935}); 936 937``` 938 939## connection.isDefaultNetMetered<sup>9+</sup> 940 941isDefaultNetMetered(callback: AsyncCallback\<boolean>): void 942 943Checks whether the data traffic over the current network is metered. For example, data traffic over Wi-Fi is not metered, whereas that over cellular networks is. This API uses an asynchronous callback to return the result. 944 945**Required permission**: ohos.permission.GET_NETWORK_INFO 946 947**System capability**: SystemCapability.Communication.NetManager.Core 948 949**Parameters** 950 951| Name | Type | Mandatory| Description | 952| -------- | ----------------------- | ---- | -------------------------------------- | 953| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** indicates that the data traffic over the current network is metered, and the value **false** indicates the opposite.| 954 955**Error codes** 956 957For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 958 959| ID| Error Message | 960| ------- | ----------------------------- | 961| 201 | Permission denied. | 962| 401 | Parameter error. | 963| 2100002 | Failed to connect to the service.| 964| 2100003 | System internal error. | 965 966**Example** 967 968```ts 969import { connection } from '@kit.NetworkKit'; 970import { BusinessError } from '@kit.BasicServicesKit'; 971 972connection.isDefaultNetMetered((error: BusinessError, data: boolean) => { 973 console.error(JSON.stringify(error)); 974 console.log('data: ' + data); 975}); 976``` 977 978## connection.isDefaultNetMetered<sup>9+</sup> 979 980isDefaultNetMetered(): Promise\<boolean> 981 982Checks whether the data traffic over the current network is metered. For example, data traffic over Wi-Fi is not metered, whereas that over cellular networks is. This API uses a promise to return the result. 983 984**Required permission**: ohos.permission.GET_NETWORK_INFO 985 986**System capability**: SystemCapability.Communication.NetManager.Core 987 988**Return value** 989 990| Type | Description | 991| ----------------- | ----------------------------------------------- | 992| Promise\<boolean> | Promise used to return the result. The value **true** indicates that the data traffic over the current network is metered, and the value **false** indicates the opposite.| 993 994**Error codes** 995 996For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 997 998| ID| Error Message | 999| ------- | -------------------------------- | 1000| 201 | Permission denied. | 1001| 2100002 | Failed to connect to the service.| 1002| 2100003 | System internal error. | 1003 1004**Example** 1005 1006```ts 1007import { connection } from '@kit.NetworkKit'; 1008 1009connection.isDefaultNetMetered().then((data: boolean) => { 1010 console.log('data: ' + data); 1011}); 1012``` 1013 1014## connection.isDefaultNetMeteredSync<sup>10+</sup> 1015 1016isDefaultNetMeteredSync(): boolean 1017 1018Checks whether the data traffic over the current network is metered. For example, data traffic over Wi-Fi is not metered, whereas that over cellular networks is. This API returns the result synchronously. 1019 1020**Required permission**: ohos.permission.GET_NETWORK_INFO 1021 1022**System capability**: SystemCapability.Communication.NetManager.Core 1023 1024**Return value** 1025 1026| Type | Description | 1027| ----------------- | ----------------------------------------------- | 1028| boolean | Boolean value indicating whether data traffic over the current network is metered. The value **true** indicates that the data traffic is metered, and the value **false** indicates the opposite.| 1029 1030**Error codes** 1031 1032For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1033 1034| ID| Error Message | 1035| ------- | -------------------------------- | 1036| 201 | Permission denied. | 1037| 2100002 | Failed to connect to the service.| 1038| 2100003 | System internal error. | 1039 1040**Example** 1041 1042```ts 1043import { connection } from '@kit.NetworkKit'; 1044 1045let isMetered = connection.isDefaultNetMeteredSync(); 1046``` 1047 1048## connection.hasDefaultNet 1049 1050hasDefaultNet(callback: AsyncCallback\<boolean>): void 1051 1052Checks whether the default data network is activated. This API uses an asynchronous callback to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any. 1053 1054**Required permission**: ohos.permission.GET_NETWORK_INFO 1055 1056**System capability**: SystemCapability.Communication.NetManager.Core 1057 1058**Parameters** 1059 1060| Name | Type | Mandatory| Description | 1061| -------- | ----------------------- | ---- | -------------------------------------- | 1062| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** indicates that the default data network is activated, and the value **false** indicates the opposite.| 1063 1064**Error codes** 1065 1066For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1067 1068| ID| Error Message | 1069| ------- | --------------------------------- | 1070| 201 | Permission denied. | 1071| 401 | Parameter error. | 1072| 2100002 | Failed to connect to the service. | 1073| 2100003 | System internal error. | 1074 1075**Example** 1076 1077```ts 1078import { connection } from '@kit.NetworkKit'; 1079import { BusinessError } from '@kit.BasicServicesKit'; 1080 1081connection.hasDefaultNet((error: BusinessError, data: boolean) => { 1082 console.error(JSON.stringify(error)); 1083 console.log('data: ' + data); 1084}); 1085``` 1086 1087## connection.hasDefaultNet 1088 1089hasDefaultNet(): Promise\<boolean> 1090 1091Checks whether the default data network is activated. This API uses a promise to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any. 1092 1093**Required permission**: ohos.permission.GET_NETWORK_INFO 1094 1095**System capability**: SystemCapability.Communication.NetManager.Core 1096 1097**Return value** 1098 1099| Type | Description | 1100| ----------------- | ----------------------------------------------- | 1101| Promise\<boolean> | Promise used to return the result. The value **true** indicates that the default data network is activated, and the value **false** indicates the opposite.| 1102 1103**Error codes** 1104 1105For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1106 1107| ID| Error Message | 1108| ------- | ----------------------------- | 1109| 201 | Permission denied. | 1110| 2100002 | Failed to connect to the service. | 1111| 2100003 | System internal error. | 1112 1113**Example** 1114 1115```ts 1116import { connection } from '@kit.NetworkKit'; 1117 1118connection.hasDefaultNet().then((data: boolean) => { 1119 console.log('data: ' + data); 1120}); 1121``` 1122 1123## connection.hasDefaultNetSync<sup>10+</sup> 1124 1125hasDefaultNetSync(): boolean 1126 1127Checks whether the default data network is activated. This API returns the result synchronously. 1128 1129**Required permission**: ohos.permission.GET_NETWORK_INFO 1130 1131**System capability**: SystemCapability.Communication.NetManager.Core 1132 1133**Return value** 1134 1135| Type | Description | 1136| ----------------- | ----------------------------------------------- | 1137| boolean | Boolean value indicating whether the default data network is activated. The value **true** indicates that the default data network is activated, and the value **false** indicates the opposite.| 1138 1139**Error codes** 1140 1141For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1142 1143| ID| Error Message | 1144| ------- | ----------------------------- | 1145| 201 | Permission denied. | 1146| 2100002 | Failed to connect to the service.| 1147| 2100003 | System internal error. | 1148 1149**Example** 1150 1151```ts 1152import { connection } from '@kit.NetworkKit'; 1153 1154let isDefaultNet = connection.hasDefaultNetSync(); 1155``` 1156 1157 1158## connection.reportNetConnected 1159 1160reportNetConnected(netHandle: NetHandle, callback: AsyncCallback<void>): void 1161 1162Reports a network connection event to the network management module. This API uses an asynchronous callback to return the result. 1163 1164**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET 1165 1166**System capability**: SystemCapability.Communication.NetManager.Core 1167 1168**Parameters** 1169 1170| Name| Type| Mandatory| Description| 1171| -------- | -------- | -------- | -------- | 1172| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| 1173| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the network status is reported successfully, **error** is **undefined**. Otherwise, **error** is an error object.| 1174 1175**Error codes** 1176 1177For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1178 1179| ID| Error Message | 1180| ------- | ----------------------------- | 1181| 201 | Permission denied. | 1182| 401 | Parameter error. | 1183| 2100001 | Invalid parameter value. | 1184| 2100002 | Failed to connect to the service. | 1185| 2100003 | System internal error. | 1186 1187**Example** 1188 1189```ts 1190import { connection } from '@kit.NetworkKit'; 1191import { BusinessError } from '@kit.BasicServicesKit'; 1192 1193connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 1194 connection.reportNetConnected(netHandle, (error: BusinessError) => { 1195 console.error(JSON.stringify(error)); 1196 }); 1197}); 1198``` 1199 1200## connection.reportNetConnected 1201 1202reportNetConnected(netHandle: NetHandle): Promise\<void\> 1203 1204Reports a network connection event to the network management module. This API uses a promise to return the result. 1205 1206**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET 1207 1208**System capability**: SystemCapability.Communication.NetManager.Core 1209 1210**Parameters** 1211 1212| Name| Type| Mandatory| Description| 1213| -------- | -------- | -------- | -------- | 1214| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| 1215 1216**Return value** 1217| Type| Description| 1218| -------- | -------- | 1219| Promise<void> | Promise that returns no value.| 1220 1221**Error codes** 1222 1223For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md). 1224 1225| ID| Error Message | 1226| ------- | --------------------------------- | 1227| 201 | Permission denied. | 1228| 401 | Parameter error. | 1229| 2100001 | Invalid parameter value. | 1230| 2100002 | Failed to connect to the service. | 1231| 2100003 | System internal error. | 1232 1233**Example** 1234 1235```ts 1236import { connection } from '@kit.NetworkKit'; 1237 1238connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 1239 connection.reportNetConnected(netHandle).then(() => { 1240 console.log(`report success`); 1241 }); 1242}); 1243``` 1244 1245## connection.reportNetDisconnected 1246 1247reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback<void>): void 1248 1249Reports a network disconnection event to the network management module. This API uses an asynchronous callback to return the result. 1250 1251**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET 1252 1253**System capability**: SystemCapability.Communication.NetManager.Core 1254 1255**Parameters** 1256 1257| Name| Type| Mandatory| Description| 1258| -------- | -------- | -------- | -------- | 1259| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| 1260| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the network status is reported successfully, **error** is **undefined**. Otherwise, **error** is an error object.| 1261 1262**Error codes** 1263 1264For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1265 1266| ID| Error Message | 1267| ------- | ----------------------------- | 1268| 201 | Permission denied. | 1269| 401 | Parameter error. | 1270| 2100001 | Invalid parameter value. | 1271| 2100002 | Failed to connect to the service. | 1272| 2100003 | System internal error. | 1273 1274**Example** 1275 1276```ts 1277import { connection } from '@kit.NetworkKit'; 1278import { BusinessError } from '@kit.BasicServicesKit'; 1279 1280connection.getDefaultNet((error: BusinessError, netHandle: connection.NetHandle) => { 1281 if (netHandle.netId == 0) { 1282 // If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements. 1283 return; 1284 } 1285 connection.reportNetDisconnected(netHandle, (error: BusinessError, data: void) => { 1286 if (error) { 1287 console.error(`Failed to get default net. Code:${error.code}, message:${error.message}`); 1288 return; 1289 } 1290 console.info("report success"); 1291 }); 1292}); 1293``` 1294 1295## connection.reportNetDisconnected 1296 1297reportNetDisconnected(netHandle: NetHandle): Promise<void> 1298 1299Reports a network disconnection event to the network management module. This API uses a promise to return the result. 1300 1301**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET 1302 1303**System capability**: SystemCapability.Communication.NetManager.Core 1304 1305**Parameters** 1306 1307| Name| Type| Mandatory| Description| 1308| -------- | -------- | -------- | -------- | 1309| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| 1310 1311**Return value** 1312| Type| Description| 1313| -------- | -------- | 1314| Promise<void> | Promise that returns no value.| 1315 1316**Error codes** 1317 1318For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1319 1320| ID| Error Message | 1321| ------- | --------------------------------- | 1322| 201 | Permission denied. | 1323| 401 | Parameter error. | 1324| 2100001 | Invalid parameter value. | 1325| 2100002 | Failed to connect to the service. | 1326| 2100003 | System internal error. | 1327 1328**Example** 1329 1330```ts 1331import { connection } from '@kit.NetworkKit'; 1332 1333connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 1334 connection.reportNetDisconnected(netHandle).then( () => { 1335 console.log(`report success`); 1336 }); 1337}); 1338``` 1339 1340## connection.getAddressesByName 1341 1342getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void 1343 1344Obtains all IP addresses by using the specified network to resolve the host name. This API uses an asynchronous callback to return the result. 1345 1346**Required permissions**: ohos.permission.INTERNET 1347 1348**System capability**: SystemCapability.Communication.NetManager.Core 1349 1350**Parameters** 1351 1352| Name | Type | Mandatory| Description | 1353| -------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | 1354| host | string | Yes | Host name to resolve. | 1355| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. If all IP addresses are successfully obtained, **error** is **undefined**, and **data** is the list of all obtained IP addresses. Otherwise, **error** is an error object.| 1356 1357**Error codes** 1358 1359For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1360 1361| ID| Error Message | 1362| ------- | --------------------------------- | 1363| 201 | Permission denied. | 1364| 401 | Parameter error. | 1365| 2100001 | Invalid parameter value. | 1366| 2100002 | Failed to connect to the service. | 1367| 2100003 | System internal error. | 1368 1369**Example** 1370 1371```ts 1372import { connection } from '@kit.NetworkKit'; 1373import { BusinessError } from '@kit.BasicServicesKit'; 1374 1375connection.getAddressesByName("xxxx", (error: BusinessError, data: connection.NetAddress[]) => { 1376 if (error) { 1377 console.error(`Failed to get addresses. Code:${error.code}, message:${error.message}`); 1378 return; 1379 } 1380 console.info("Succeeded to get data: " + JSON.stringify(data)); 1381}); 1382``` 1383 1384## connection.getAddressesByName 1385 1386getAddressesByName(host: string): Promise\<Array\<NetAddress\>\> 1387 1388Obtains all IP addresses by using the specified network to resolve the host name. This API uses a promise to return the result. 1389 1390**Required permissions**: ohos.permission.INTERNET 1391 1392**System capability**: SystemCapability.Communication.NetManager.Core 1393 1394**Parameters** 1395 1396| Name| Type | Mandatory| Description | 1397| ------ | ------ | ---- | ------------------ | 1398| host | string | Yes | Host name to resolve.| 1399 1400**Return value** 1401 1402| Type | Description | 1403| ------------------------------------------- | ----------------------------- | 1404| Promise\<Array\<[NetAddress](#netaddress)>> | Promise used to return the result.| 1405 1406**Error codes** 1407 1408For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1409 1410| ID| Error Message | 1411| ------- | ----------------------------- | 1412| 201 | Permission denied. | 1413| 401 | Parameter error. | 1414| 2100001 | Invalid parameter value. | 1415| 2100002 | Failed to connect to the service. | 1416| 2100003 | System internal error. | 1417 1418**Example** 1419 1420```ts 1421import { connection } from '@kit.NetworkKit'; 1422 1423connection.getAddressesByName("xxxx").then((data: connection.NetAddress[]) => { 1424 console.info("Succeeded to get data: " + JSON.stringify(data)); 1425}); 1426``` 1427 1428## connection.addCustomDnsRule<sup>11+</sup> 1429 1430addCustomDnsRule(host: string, ip: Array\<string\>, callback: AsyncCallback\<void\>): void 1431 1432Adds custom DNS rules for the specified host of the current application. This API uses an asynchronous callback to return the result. 1433 1434**Required permissions**: ohos.permission.INTERNET 1435 1436**Atomic service API**: This API can be used in atomic services since API version 15. 1437 1438**System capability**: SystemCapability.Communication.NetManager.Core 1439 1440**Parameters** 1441 1442| Name | Type | Mandatory| Description | 1443| -------- | -------------------- | ---- | ------------------------------------------------------------ | 1444| host | string | Yes | Name of the custom host. | 1445| ip | Array\<string> | Yes | List of IP addresses mapped to the host name. | 1446| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the mapping is added successfully, **error** is **undefined**. Otherwise, **error** is an error object.| 1447 1448**Error codes** 1449 1450For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1451 1452| ID| Error Message | 1453| ------- | --------------------------------- | 1454| 201 | Permission denied. | 1455| 401 | Parameter error. | 1456| 2100001 | Invalid parameter value. | 1457| 2100002 | Failed to connect to the service. | 1458| 2100003 | System internal error. | 1459 1460**Example** 1461 1462```ts 1463import { connection } from '@kit.NetworkKit'; 1464import { BusinessError } from '@kit.BasicServicesKit'; 1465 1466connection.addCustomDnsRule("xxxx", ["xx.xx.xx.xx","xx.xx.xx.xx"], (error: BusinessError, data: void) => { 1467 if (error) { 1468 console.error(`Failed to get add custom dns rule. Code:${error.code}, message:${error.message}`); 1469 return; 1470 } 1471 console.info("Succeeded to get data: " + JSON.stringify(data)); 1472}) 1473``` 1474 1475## connection.addCustomDnsRule<sup>11+</sup> 1476 1477addCustomDnsRule(host: string, ip: Array\<string\>): Promise\<void\> 1478 1479Adds custom DNS rules for the specified host of the current application. This API uses a promise to return the result. 1480 1481**Required permissions**: ohos.permission.INTERNET 1482 1483**Atomic service API**: This API can be used in atomic services since API version 15. 1484 1485**System capability**: SystemCapability.Communication.NetManager.Core 1486 1487**Parameters** 1488 1489| Name| Type | Mandatory| Description | 1490| ------ | -------------- | ---- | -------------------------- | 1491| host | string | Yes | Name of the custom host. | 1492| ip | Array\<string> | Yes | List of IP addresses mapped to the host name.| 1493 1494**Return value** 1495 1496| Type | Description | 1497| ---------------------- | ----------------------- | 1498| Promise\<void> | Promise that returns no value.| 1499 1500**Error codes** 1501 1502For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1503 1504| ID| Error Message | 1505| ------- | --------------------------------- | 1506| 201 | Permission denied. | 1507| 401 | Parameter error. | 1508| 2100001 | Invalid parameter value. | 1509| 2100002 | Failed to connect to the service. | 1510| 2100003 | System internal error. | 1511 1512**Example** 1513 1514```ts 1515import { connection } from '@kit.NetworkKit'; 1516import { BusinessError } from '@kit.BasicServicesKit'; 1517 1518connection.addCustomDnsRule("xxxx", ["xx.xx.xx.xx","xx.xx.xx.xx"]).then(() => { 1519 console.info("success"); 1520}).catch((error: BusinessError) => { 1521 console.error(JSON.stringify(error)); 1522}) 1523``` 1524 1525## connection.removeCustomDnsRule<sup>11+</sup> 1526 1527removeCustomDnsRule(host: string, callback: AsyncCallback\<void\>): void 1528 1529Removes the custom DNS rules of the specified host from the current application. This API uses an asynchronous callback to return the result. 1530 1531**Required permissions**: ohos.permission.INTERNET 1532 1533**Atomic service API**: This API can be used in atomic services since API version 15. 1534 1535**System capability**: SystemCapability.Communication.NetManager.Core 1536 1537**Parameters** 1538 1539| Name | Type | Mandatory| Description | 1540| -------- | -------------------- | ---- | ------------------------------------------------------------ | 1541| host | string | Yes | Name of the host for which DNS rules are to be deleted. | 1542| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the DNS rules are removed successfully, **error** is **undefined**. Otherwise, **error** is an error object.| 1543 1544**Error codes** 1545 1546For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1547 1548| ID| Error Message | 1549| ------- | ----------------------------- | 1550| 201 | Permission denied. | 1551| 401 | Parameter error. | 1552| 2100001 | Invalid parameter value. | 1553| 2100002 | Failed to connect to the service. | 1554| 2100003 | System internal error. | 1555 1556**Example** 1557 1558```ts 1559import { connection } from '@kit.NetworkKit'; 1560import { BusinessError } from '@kit.BasicServicesKit'; 1561 1562connection.removeCustomDnsRule("xxxx", (error: BusinessError, data: void) => { 1563 if (error) { 1564 console.error(`Failed to remove custom dns rule. Code:${error.code}, message:${error.message}`); 1565 return; 1566 } 1567 console.info("Succeeded to get data: " + JSON.stringify(data)); 1568}) 1569``` 1570 1571## connection.removeCustomDnsRule<sup>11+</sup> 1572 1573removeCustomDnsRule(host: string): Promise\<void\> 1574 1575Removes the custom DNS rules of the specified host from the current application. This API uses a promise to return the result. 1576 1577**Required permissions**: ohos.permission.INTERNET 1578 1579**Atomic service API**: This API can be used in atomic services since API version 15. 1580 1581**System capability**: SystemCapability.Communication.NetManager.Core 1582 1583**Parameters** 1584 1585| Name| Type | Mandatory| Description | 1586| ------ | ------ | ---- | ------------------------------- | 1587| host | string | Yes | Name of the host for which DNS rules are to be deleted.| 1588 1589**Return value** 1590 1591| Type | Description | 1592| ---------------------- | ----------------------- | 1593| Promise\<void> | Promise that returns no value.| 1594 1595**Error codes** 1596 1597For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1598 1599| ID| Error Message | 1600| ------- | --------------------------------- | 1601| 201 | Permission denied. | 1602| 401 | Parameter error. | 1603| 2100001 | Invalid parameter value. | 1604| 2100002 | Failed to connect to the service. | 1605| 2100003 | System internal error. | 1606 1607**Example** 1608 1609```ts 1610import { connection } from '@kit.NetworkKit'; 1611import { BusinessError } from '@kit.BasicServicesKit'; 1612 1613connection.removeCustomDnsRule("xxxx").then(() => { 1614 console.log("success"); 1615}).catch((error: BusinessError) => { 1616 console.error(JSON.stringify(error)); 1617}) 1618``` 1619 1620## connection.clearCustomDnsRules<sup>11+</sup> 1621 1622clearCustomDnsRules(callback: AsyncCallback\<void\>): void 1623 1624Removes all custom DNS rules from the current application. This API uses an asynchronous callback to return the result. 1625 1626**Required permissions**: ohos.permission.INTERNET 1627 1628**System capability**: SystemCapability.Communication.NetManager.Core 1629 1630**Parameters** 1631 1632| Name | Type | Mandatory| Description | 1633| -------- | -------------------- | ---- | ------------------------------------------------------------ | 1634| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If all the DNS rules are removed successfully, **error** is **undefined**. Otherwise, **error** is an error object.| 1635 1636**Error codes** 1637 1638For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1639 1640| ID| Error Message | 1641| ------- | --------------------------------- | 1642| 201 | Permission denied. | 1643| 401 | Parameter error. | 1644| 2100001 | Invalid parameter value. | 1645| 2100002 | Failed to connect to the service. | 1646| 2100003 | System internal error. | 1647 1648**Example** 1649 1650```ts 1651import { connection } from '@kit.NetworkKit'; 1652import { BusinessError } from '@kit.BasicServicesKit'; 1653 1654connection.clearCustomDnsRules((error: BusinessError, data: void) => { 1655 if (error) { 1656 console.error(`Failed to clear custom dns rules. Code:${error.code}, message:${error.message}`); 1657 return; 1658 } 1659 console.info("Succeeded to get data: " + JSON.stringify(data)); 1660}) 1661``` 1662 1663## connection.clearCustomDnsRules<sup>11+</sup> 1664 1665clearCustomDnsRules(): Promise\<void\> 1666 1667Removes all custom DNS rules from the current application. This API uses a promise to return the result. 1668 1669**Required permissions**: ohos.permission.INTERNET 1670 1671**System capability**: SystemCapability.Communication.NetManager.Core 1672 1673**Return value** 1674 1675| Type | Description | 1676| ---------------------- | ----------------------- | 1677| Promise\<void\> | Promise that returns no value. | 1678 1679**Error codes** 1680 1681For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1682 1683| ID| Error Message | 1684| ------- | --------------------------------- | 1685| 201 | Permission denied. | 1686| 2100001 | Invalid parameter value. | 1687| 2100002 | Failed to connect to the service. | 1688| 2100003 | System internal error. | 1689 1690**Example** 1691 1692```ts 1693import { connection } from '@kit.NetworkKit'; 1694import { BusinessError } from '@kit.BasicServicesKit'; 1695 1696connection.clearCustomDnsRules().then(() => { 1697 console.log("success"); 1698}).catch((error: BusinessError) => { 1699 console.error(JSON.stringify(error)); 1700}) 1701``` 1702 1703## connection.setPacUrl<sup>15+</sup> 1704 1705setPacUrl(pacUrl: string): void 1706 1707Sets the URL of the system-level Proxy Auto Config (PAC) script. 1708 1709**Required permissions**: ohos.permission.SET_PAC_URL 1710 1711**System capability**: SystemCapability.Communication.NetManager.Core 1712 1713**Parameters** 1714 1715| Name | Type | Mandatory| Description | 1716| -------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | 1717| pacUrl | string | Yes | URL of the PAC script. Note that this URL will not be verified by the API. | 1718 1719**Error codes** 1720 1721For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1722 1723| ID| Error Message | 1724| ------- | --------------------------------- | 1725| 201 | Permission denied. | 1726| 401 | Parameter error. | 1727| 2100002 | Failed to connect to the service. | 1728| 2100003 | System internal error. | 1729 1730**Example** 1731 1732```ts 1733import { connection } from '@kit.NetworkKit'; 1734 1735let pacUrl = "xxx"; 1736connection.setPacUrl(pacUrl); 1737``` 1738 1739## connection.getPacUrl<sup>15+</sup> 1740 1741getPacUrl(): string 1742 1743Obtains the URL of the system-level PAC script. 1744 1745**System capability**: SystemCapability.Communication.NetManager.Core 1746 1747**Return value** 1748 1749| Type | Description | 1750| ---------------------- | ----------------------- | 1751| string | URL of the PAC script. If the PAC script does not exist, error code 2100003 is reported. | 1752 1753**Error codes** 1754 1755For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md). 1756 1757| ID| Error Message | 1758| ------- | --------------------------------- | 1759| 2100002 | Failed to connect to the service. | 1760| 2100003 | System internal error. | 1761 1762**Example** 1763 1764```ts 1765import { connection } from '@kit.NetworkKit'; 1766 1767let pacUrl = connection.getPacUrl(); 1768``` 1769 1770## connection.setNetExtAttribute<sup>20+</sup> 1771 1772setNetExtAttribute(netHandle: NetHandle, netExtAttribute: string): Promise\<void\> 1773 1774Sets extended attributes of the network specified by **netHandle** to indicate its security level. This API uses a promise to return the result. 1775 1776> **NOTE** 1777> Currently, this API is available only for PCs. 1778 1779**Required permissions**: ohos.permission.SET_NET_EXT_ATTRIBUTE 1780 1781**System capability**: SystemCapability.Communication.NetManager.Core 1782 1783**Parameters** 1784 1785| Name | Type | Mandatory| Description | 1786| --------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | 1787| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network. | 1788| netExtAttribute | string | Yes | Extended network attributes. | 1789 1790**Return value** 1791 1792| Type | Description | 1793| ---------------------- | ----------------------- | 1794| Promise\<void\> | Promise that returns no value.| 1795 1796**Error codes** 1797 1798For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1799 1800| ID| Error Message | 1801| ------- | --------------------------------- | 1802| 201 | Permission denied. | 1803| 2100001 | Invalid parameter value. | 1804| 2100002 | Failed to connect to the service. | 1805| 2100003 | System internal error. | 1806 1807**Example** 1808 1809```ts 1810import { connection } from '@kit.NetworkKit'; 1811import { BusinessError } from '@kit.BasicServicesKit'; 1812 1813connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 1814 if (netHandle.netId == 0) { 1815 // If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements. 1816 return; 1817 } 1818 let netExtAttribute: string = "xxx"; 1819 connection.setNetExtAttribute(netHandle, netExtAttribute).then(() => { 1820 console.info("setNetExtAttribute success"); 1821 }).catch((error: BusinessError) => { 1822 console.error("setNetExtAttribute failed, err: " + error.code); 1823 }) 1824}); 1825``` 1826 1827## connection.setNetExtAttributeSync<sup>20+</sup> 1828 1829setNetExtAttributeSync(netHandle: NetHandle, netExtAttribute: string): void 1830 1831Sets extended attributes of the network specified by **netHandle** to indicate its security level. This API returns the result synchronously. 1832 1833> **NOTE** 1834> Currently, this API is available only on PCs. 1835 1836**Required permissions**: ohos.permission.SET_NET_EXT_ATTRIBUTE 1837 1838**System capability**: SystemCapability.Communication.NetManager.Core 1839 1840**Parameters** 1841 1842| Name | Type | Mandatory| Description | 1843| --------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | 1844| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network. | 1845| netExtAttribute | string | Yes | Extended network attributes. | 1846 1847**Error codes** 1848 1849For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1850 1851| ID| Error Message | 1852| ------- | --------------------------------- | 1853| 201 | Permission denied. | 1854| 2100001 | Invalid parameter value. | 1855| 2100002 | Failed to connect to the service. | 1856| 2100003 | System internal error. | 1857 1858**Example** 1859 1860```ts 1861import { connection } from '@kit.NetworkKit'; 1862import { BusinessError } from '@kit.BasicServicesKit'; 1863 1864let netExtAttribute: string = "xxx"; 1865let netHandle = connection.getDefaultNetSync(); 1866if (netHandle.netId != 0) { 1867 connection.setNetExtAttributeSync(netHandle, netExtAttribute); 1868} 1869``` 1870 1871## connection.getNetExtAttribute<sup>20+</sup> 1872 1873getNetExtAttribute(netHandle: NetHandle): Promise\<string\> 1874 1875Obtains the extended attributes of the network specified by **netHandle** to determine its security level. This API uses a promise to return the result. 1876 1877**Required permission**: ohos.permission.GET_NETWORK_INFO 1878 1879**System capability**: SystemCapability.Communication.NetManager.Core 1880 1881**Parameters** 1882 1883| Name | Type | Mandatory| Description | 1884| --------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | 1885| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network. | 1886 1887**Return value** 1888 1889| Type | Description | 1890| ---------------------- | ----------------------- | 1891| Promise\<string\> | Promise used to return the result. | 1892 1893**Error codes** 1894 1895For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1896 1897| ID| Error Message | 1898| ------- | --------------------------------- | 1899| 201 | Permission denied. | 1900| 2100001 | Invalid parameter value. | 1901| 2100002 | Failed to connect to the service. | 1902| 2100003 | System internal error. | 1903 1904**Example** 1905 1906```ts 1907import { connection } from '@kit.NetworkKit'; 1908import { BusinessError } from '@kit.BasicServicesKit'; 1909 1910connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 1911 if (netHandle.netId == 0) { 1912 // If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements. 1913 return; 1914 } 1915 connection.getNetExtAttribute(netHandle).then((netExtAttribute: string) => { 1916 console.info("getNetExtAttribute: " + netExtAttribute); 1917 }).catch((error: BusinessError) => { 1918 console.error("getNetExtAttribute failed, err: " + error.code); 1919 }) 1920}); 1921``` 1922 1923## connection.getNetExtAttributeSync<sup>20+</sup> 1924 1925getNetExtAttributeSync(netHandle: NetHandle): string 1926 1927Obtains the extended attributes of the network specified by **netHandle** to determine its security level. This API returns the result synchronously. 1928 1929**Required permission**: ohos.permission.GET_NETWORK_INFO 1930 1931**System capability**: SystemCapability.Communication.NetManager.Core 1932 1933**Parameters** 1934 1935| Name | Type | Mandatory| Description | 1936| --------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | 1937| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network. | 1938 1939**Return value** 1940 1941| Type | Description | 1942| ------ | ----------------------- | 1943| string | Extended network attributes.| 1944 1945 1946**Error codes** 1947 1948For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 1949 1950| ID| Error Message | 1951| ------- | --------------------------------- | 1952| 201 | Permission denied. | 1953| 2100001 | Invalid parameter value. | 1954| 2100002 | Failed to connect to the service. | 1955| 2100003 | System internal error. | 1956 1957**Example** 1958 1959```ts 1960import { connection } from '@kit.NetworkKit'; 1961import { BusinessError } from '@kit.BasicServicesKit'; 1962 1963let netHandle = connection.getDefaultNetSync(); 1964if (netHandle.netId != 0) { 1965 let netExtAttribute: string = connection.getNetExtAttributeSync(netHandle); 1966 console.info("getNetExtAttribute: " + netExtAttribute); 1967} 1968``` 1969 1970## NetConnection 1971 1972Represents the network connection handle. 1973 1974> **NOTE** 1975> 1976>(1) When the network transitions from unavailable to available, the **netAvailable**, **netCapabilitiesChange**, and **netConnectionPropertiesChange** events are triggered. 1977> 1978>(2) If the network transitions from available to unavailable after a **netAvailable** event is received, a **netLost** event is triggered. 1979> 1980>(3) If no **netAvailable** event is received, a **netUnavailable** event is directly triggered. 1981> 1982>(4) When the network transitions from Wi-Fi to cellular, a **netLost** event is first triggered to indicate that the Wi-Fi network is lost and then a **netAvailable** event is triggered to indicate that the cellular network is available. 1983 1984### register 1985 1986register(callback: AsyncCallback\<void>): void 1987 1988Registers a listener for network status changes. 1989 1990**Note**: After using this API, you need to call **unregister** to cancel the registration in a timely manner. 1991 1992**Required permission**: ohos.permission.GET_NETWORK_INFO 1993 1994**Atomic service API**: This API can be used in atomic services since API version 11. 1995 1996**System capability**: SystemCapability.Communication.NetManager.Core 1997 1998**Parameters** 1999 2000| Name | Type | Mandatory| Description | 2001| -------- | -------------------- | ---- | ------------------------------------------------------------ | 2002| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If a listener for network status changes is registered successfully, **error** is **undefined**. Otherwise, **error** is an error object.| 2003 2004**Error codes** 2005 2006For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 2007 2008| ID| Error Message | 2009| ------- | ---------------------------------------------------- | 2010| 201 | Permission denied. | 2011| 401 | Parameter error. | 2012| 2100002 | Failed to connect to the service. | 2013| 2100003 | System internal error. | 2014| 2101008 | The callback already exists. | 2015| 2101022 | The number of requests exceeded the maximum allowed. | 2016 2017**Example** 2018 2019```ts 2020import { connection } from '@kit.NetworkKit'; 2021import { BusinessError } from '@kit.BasicServicesKit'; 2022 2023let netCon: connection.NetConnection = connection.createNetConnection(); 2024netCon.register((error: BusinessError) => { 2025 console.error(JSON.stringify(error)); 2026}); 2027``` 2028 2029### unregister 2030 2031unregister(callback: AsyncCallback\<void>): void 2032 2033Unregisters the listener for network status changes. 2034 2035**Atomic service API**: This API can be used in atomic services since API version 11. 2036 2037**System capability**: SystemCapability.Communication.NetManager.Core 2038 2039**Parameters** 2040 2041| Name | Type | Mandatory| Description | 2042| -------- | -------------------- | ---- | ------------------------------------------------------------ | 2043| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If a listener for network status changes is unregistered successfully, **error** is **undefined**. Otherwise, **error** is an error object.| 2044 2045**Error codes** 2046 2047For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 2048 2049| ID| Error Message | 2050| ------- | --------------------------------- | 2051| 401 | Parameter error. | 2052| 2100002 | Failed to connect to the service. | 2053| 2100003 | System internal error. | 2054| 2101007 | The callback does not exist. | 2055 2056**Example** 2057 2058```ts 2059import { connection } from '@kit.NetworkKit'; 2060import { BusinessError } from '@kit.BasicServicesKit'; 2061 2062let netCon: connection.NetConnection = connection.createNetConnection(); 2063netCon.unregister((error: BusinessError) => { 2064 console.error(JSON.stringify(error)); 2065}); 2066``` 2067 2068### on('netAvailable') 2069 2070on(type: 'netAvailable', callback: Callback\<NetHandle>): void 2071 2072Registers a listener for **netAvailable** events. Before you call this API, make sure that you have called **register** to add a listener for network status changes. When the listener is no longer needed, call **unregister** to remove it. 2073 2074**Atomic service API**: This API can be used in atomic services since API version 11. 2075 2076**System capability**: SystemCapability.Communication.NetManager.Core 2077 2078**Parameters** 2079 2080| Name | Type | Mandatory| Description | 2081| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | 2082| type | string | Yes | Event type. This field has a fixed value of **netAvailable**.<br>**netAvailable**: event indicating that the data network is available.| 2083| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the network handle.| 2084 2085**Example** 2086 2087```ts 2088import { connection } from '@kit.NetworkKit'; 2089import { BusinessError } from '@kit.BasicServicesKit'; 2090 2091// Create a NetConnection object. 2092let netCon: connection.NetConnection = connection.createNetConnection(); 2093 2094// Use the register API to subscribe to network status change events. 2095netCon.register((error: BusinessError) => { 2096 console.error(JSON.stringify(error)); 2097}); 2098 2099// Use the register API to subscribe to netAvailable events. 2100netCon.on('netAvailable', (data: connection.NetHandle) => { 2101 console.info("Succeeded to get data: " + JSON.stringify(data)); 2102}); 2103 2104// Use the unregister API to unsubscribe from netAvailable events. 2105netCon.unregister((error: BusinessError) => { 2106 console.error(JSON.stringify(error)); 2107}); 2108``` 2109 2110### on('netBlockStatusChange') 2111 2112on(type: 'netBlockStatusChange', callback: Callback\<NetBlockStatusInfo>): void 2113 2114Registers a listener for **netBlockStatusChange** events. Before you call this API, make sure that you have called **register** to add a listener for network status changes. When the listener is no longer needed, call **unregister** to remove it. 2115 2116**System capability**: SystemCapability.Communication.NetManager.Core 2117 2118**Parameters** 2119 2120| Name | Type | Mandatory| Description | 2121| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 2122| type | string | Yes | Event type. This field has a fixed value of **netBlockStatusChange**.<br>**netBlockStatusChange**: event indicating a change in the network blocking status.| 2123| callback | Callback<[NetBlockStatusInfo](#netblockstatusinfo11)> | Yes | Callback used to return the result.| 2124 2125**Example** 2126 2127```ts 2128import { connection } from '@kit.NetworkKit'; 2129import { BusinessError } from '@kit.BasicServicesKit'; 2130 2131// Create a NetConnection object. 2132let netCon: connection.NetConnection = connection.createNetConnection(); 2133 2134// Use the register API to subscribe to network status change events. 2135netCon.register((error: BusinessError) => { 2136 console.error(JSON.stringify(error)); 2137}); 2138 2139// Subscribe to netBlockStatusChange events. Before that, make sure you have called the register API to add a listener. 2140netCon.on('netBlockStatusChange', (data: connection.NetBlockStatusInfo) => { 2141 console.info("Succeeded to get data: " + JSON.stringify(data)); 2142}); 2143 2144// Use the unregister API to remove the listener for netBlockStatusChange events. 2145netCon.unregister((error: BusinessError) => { 2146 console.error(JSON.stringify(error)); 2147}); 2148``` 2149 2150### on('netCapabilitiesChange') 2151 2152on(type: 'netCapabilitiesChange', callback: Callback\<NetCapabilityInfo\>): void 2153 2154Registers a listener for **netCapabilitiesChange** events. Before you call this API, make sure that you have called **register** to add a listener for network status changes. When the listener is no longer needed, call **unregister** to remove it. 2155 2156**Atomic service API**: This API can be used in atomic services since API version 11. 2157 2158**System capability**: SystemCapability.Communication.NetManager.Core 2159 2160**Parameters** 2161 2162| Name | Type | Mandatory| Description | 2163| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 2164| type | string | Yes | Event type. This field has a fixed value of **netCapabilitiesChange**.<br>**netCapabilitiesChange**: event indicating that the network capabilities have changed.| 2165| callback | Callback<[NetCapabilityInfo](#netcapabilityinfo10)> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).| 2166 2167**Example** 2168 2169```ts 2170import { connection } from '@kit.NetworkKit'; 2171import { BusinessError } from '@kit.BasicServicesKit'; 2172 2173// Create a NetConnection object. 2174let netCon: connection.NetConnection = connection.createNetConnection(); 2175 2176// Use the register API to subscribe to network status change events. 2177netCon.register((error: BusinessError) => { 2178 console.error(JSON.stringify(error)); 2179}); 2180 2181// Subscribe to netCapabilitiesChange events. Before that, make sure you have called the register API to add a listener. 2182netCon.on('netCapabilitiesChange', (data: connection.NetCapabilityInfo) => { 2183 console.info("Succeeded to get data: " + JSON.stringify(data)); 2184}); 2185 2186// Unsubscribe from netCapabilitiesChange events. 2187netCon.unregister((error: BusinessError) => { 2188 console.error(JSON.stringify(error)); 2189}); 2190``` 2191 2192### on('netConnectionPropertiesChange') 2193 2194on(type: 'netConnectionPropertiesChange', callback: Callback\<NetConnectionPropertyInfo\>): void 2195 2196Registers a listener for **netConnectionPropertiesChange** events. Before you call this API, make sure that you have called **register** to add a listener for network status changes. When the listener is no longer needed, call **unregister** to remove it. 2197 2198**System capability**: SystemCapability.Communication.NetManager.Core 2199 2200**Parameters** 2201 2202| Name | Type | Mandatory| Description | 2203| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 2204| type | string | Yes | Event type. This field has a fixed value of **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.| 2205| callback | Callback<[NetConnectionPropertyInfo](#netconnectionpropertyinfo11)> | Yes | Callback used to return the result.| 2206 2207**Example** 2208 2209```ts 2210import { connection } from '@kit.NetworkKit'; 2211import { BusinessError } from '@kit.BasicServicesKit'; 2212 2213// Create a NetConnection object. 2214let netCon: connection.NetConnection = connection.createNetConnection(); 2215 2216// Use the register API to subscribe to network status change events. 2217netCon.register((error: BusinessError) => { 2218 console.error(JSON.stringify(error)); 2219}); 2220 2221// Subscribe to netConnectionPropertiesChange events. Before that, make sure you have called the register API to add a listener. 2222netCon.on('netConnectionPropertiesChange', (data: connection.NetConnectionPropertyInfo) => { 2223 console.info("Succeeded to get data: " + JSON.stringify(data)); 2224}); 2225 2226// Use the unregister API to remove the listener for netConnectionPropertiesChange events. 2227netCon.unregister((error: BusinessError) => { 2228 console.error(JSON.stringify(error)); 2229}); 2230``` 2231 2232### on('netLost') 2233 2234on(type: 'netLost', callback: Callback\<NetHandle>): void 2235 2236Registers a listener for **netLost** events. Before you call this API, make sure that you have called **register** to add a listener for network status changes. When the listener is no longer needed, call **unregister** to remove it. 2237 2238**Atomic service API**: This API can be used in atomic services since API version 11. 2239 2240**System capability**: SystemCapability.Communication.NetManager.Core 2241 2242**Parameters** 2243 2244| Name | Type | Mandatory| Description | 2245| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | 2246| type | string | Yes | Event type. This field has a fixed value of **netLost**.<br>**netLost**: event indicating that the network is interrupted or normally disconnected.| 2247| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result, which is a **netHandle** object.| 2248 2249**Example** 2250 2251```ts 2252import { connection } from '@kit.NetworkKit'; 2253import { BusinessError } from '@kit.BasicServicesKit'; 2254 2255// Create a NetConnection object. 2256let netCon: connection.NetConnection = connection.createNetConnection(); 2257 2258// Use the register API to subscribe to network status change events. 2259netCon.register((error: BusinessError) => { 2260 console.error(JSON.stringify(error)); 2261}); 2262 2263// Subscribe to netLost events. Before that, make sure you have called the register API to add a listener. 2264netCon.on('netLost', (data: connection.NetHandle) => { 2265 console.info("Succeeded to get data: " + JSON.stringify(data)); 2266}); 2267 2268// Use the unregister API to remove the listener for netLost events. 2269netCon.unregister((error: BusinessError) => { 2270 console.error(JSON.stringify(error)); 2271}); 2272``` 2273 2274### on('netUnavailable') 2275 2276on(type: 'netUnavailable', callback: Callback\<void>): void 2277 2278Registers a listener for **netUnavailable** events. Before you call this API, make sure that you have called **register** to add a listener for network status changes. When the listener is no longer needed, call **unregister** to remove it. 2279 2280**Atomic service API**: This API can be used in atomic services since API version 11. 2281 2282**System capability**: SystemCapability.Communication.NetManager.Core 2283 2284**Parameters** 2285 2286| Name | Type | Mandatory| Description | 2287| -------- | --------------- | ---- | ------------------------------------------------------------ | 2288| type | string | Yes | Event type. This field has a fixed value of **netUnavailable**.<br>**netUnavailable**: event indicating that the network is unavailable.| 2289| callback | Callback\<void> | Yes | Callback used to return the result, which is empty.| 2290 2291**Example** 2292 2293```ts 2294import { connection } from '@kit.NetworkKit'; 2295import { BusinessError } from '@kit.BasicServicesKit'; 2296 2297// Create a NetConnection object. 2298let netCon: connection.NetConnection = connection.createNetConnection(); 2299 2300// Use the register API to subscribe to network status change events. 2301netCon.register((error: BusinessError) => { 2302 console.error(JSON.stringify(error)); 2303}); 2304 2305// Subscribe to netUnavailable events. Before that, make sure you have called the register API to add a listener. 2306netCon.on('netUnavailable', () => { 2307 console.info("Succeeded to get unavailable net event"); 2308}); 2309 2310// Use the unregister API to remove the listener for netUnavailable events. 2311netCon.unregister((error: BusinessError) => { 2312 console.error(JSON.stringify(error)); 2313}); 2314``` 2315 2316## NetHandle 2317 2318Defines the handle of the data network. 2319 2320Before invoking **NetHandle** APIs, call **getNetHandle** to obtain a **NetHandle** object. 2321 2322**System capability**: SystemCapability.Communication.NetManager.Core 2323 2324### Attributes 2325 2326| Name | Type | Mandatory| Description | 2327| ------ | ------ | --- |------------------------- | 2328| netId | number | Yes | Network ID. The value **0** indicates no default network. Any other value must be greater than or equal to 100.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2329 2330### bindSocket<sup>9+</sup> 2331 2332bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>): void 2333 2334Binds the TCPSocket or UDPSocket to the network specified by **NetHandle**. This API uses an asynchronous callback to return the result. 2335 2336**System capability**: SystemCapability.Communication.NetManager.Core 2337 2338**Parameters** 2339 2340| Name | Type | Mandatory| Description | 2341| ----------- | ------------------------ | ---- | -------------------------------| 2342| socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | Yes| **TCPSocket** or **UDPSocket** object.| 2343| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the **TCPSocket** or **UDPSocket** object is successfully bound to the current network, **error** is **undefined**. Otherwise, **error** is an error object.| 2344 2345**Error codes** 2346 2347For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 2348 2349| ID| Error Message | 2350| ------- | --------------------------------- | 2351| 401 | Parameter error. | 2352| 2100001 | Invalid parameter value. | 2353| 2100002 | Failed to connect to the service. | 2354| 2100003 | System internal error. | 2355 2356**Example** 2357 2358```ts 2359import { connection, socket } from '@kit.NetworkKit'; 2360import { BusinessError } from '@kit.BasicServicesKit'; 2361 2362interface Data { 2363 message: ArrayBuffer, 2364 remoteInfo: socket.SocketRemoteInfo 2365} 2366 2367 connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 2368 if (netHandle.netId == 0) { 2369 // If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements. 2370 } 2371 let tcp : socket.TCPSocket = socket.constructTCPSocketInstance(); 2372 let udp : socket.UDPSocket = socket.constructUDPSocketInstance(); 2373 let socketType = "TCPSocket"; 2374 if (socketType == "TCPSocket") { 2375 tcp.bind({address:"192.168.xxx.xxx", 2376 port:8080, 2377 family:1} as socket.NetAddress, (error: Error) => { 2378 if (error) { 2379 console.error('bind fail'); 2380 return; 2381 } 2382 netHandle.bindSocket(tcp, (error: BusinessError, data: void) => { 2383 if (error) { 2384 console.error(`Failed to bind socket. Code:${error.code}, message:${error.message}`); 2385 return; 2386 } else { 2387 console.info(JSON.stringify(data)); 2388 } 2389 }); 2390 }); 2391 } else { 2392 let callback: (value: Data) => void = (value: Data) => { 2393 console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); 2394 }; 2395 udp.bind({address:"192.168.xxx.xxx", 2396 port:8080, 2397 family:1} as socket.NetAddress, (error: BusinessError) => { 2398 if (error) { 2399 console.error(`Failed to bind. Code:${error.code}, message:${error.message}`); 2400 return; 2401 } 2402 udp.on('message', (data: Data) => { 2403 console.info("Succeeded to get data: " + JSON.stringify(data)); 2404 }); 2405 netHandle.bindSocket(udp, (error: BusinessError, data: void) => { 2406 if (error) { 2407 console.error(`Failed to bind socket. Code:${error.code}, message:${error.message}`); 2408 return; 2409 } else { 2410 console.info(JSON.stringify(data)); 2411 } 2412 }); 2413 }); 2414 } 2415}) 2416``` 2417 2418### bindSocket<sup>9+</sup> 2419 2420bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\<void\> 2421 2422Binds the TCPSocket or UDPSocket to the network specified by **NetHandle**. This API uses a promise to return the result. 2423 2424**System capability**: SystemCapability.Communication.NetManager.Core 2425 2426**Parameters** 2427 2428| Name | Type | Mandatory | Description | 2429| --------------- | --------------------- | ---- | ------------------------------ | 2430| socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | Yes | **TCPSocket** or **UDPSocket** object.| 2431 2432**Return value** 2433 2434| Type | Description | 2435| -------------- | ---------------------- | 2436| Promise\<void\> | Promise that returns no value.| 2437 2438**Error codes** 2439 2440For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 2441 2442| ID| Error Message | 2443| ------- | --------------------------------- | 2444| 401 | Parameter error. | 2445| 2100001 | Invalid parameter value. | 2446| 2100002 | Failed to connect to the service. | 2447| 2100003 | System internal error. | 2448 2449**Example** 2450 2451```ts 2452import { connection, socket } from '@kit.NetworkKit'; 2453import { BusinessError } from '@kit.BasicServicesKit'; 2454 2455interface Data { 2456 message: ArrayBuffer, 2457 remoteInfo: socket.SocketRemoteInfo 2458} 2459 2460connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 2461 if (netHandle.netId == 0) { 2462 // If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements. 2463 return; 2464 } 2465 let tcp : socket.TCPSocket = socket.constructTCPSocketInstance(); 2466 let udp : socket.UDPSocket = socket.constructUDPSocketInstance(); 2467 let socketType = "TCPSocket"; 2468 if (socketType == "TCPSocket") { 2469 tcp.bind({address:"192.168.xxx.xxx", 2470 port:8080, 2471 family:1} as socket.NetAddress, (error: Error) => { 2472 if (error) { 2473 console.error('bind fail'); 2474 return; 2475 } 2476 netHandle.bindSocket(tcp).then(() => { 2477 console.info("bind socket success"); 2478 }).catch((error: BusinessError) => { 2479 console.error(`Failed to bind socket. Code:${error.code}, message:${error.message}`); 2480 }); 2481 }); 2482 } else { 2483 let callback: (value: Data) => void = (value: Data) => { 2484 console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); 2485 } 2486 udp.bind({address:"192.168.xxx.xxx", 2487 port:8080, 2488 family:1} as socket.NetAddress, (error: BusinessError) => { 2489 if (error) { 2490 console.error(`Failed to bind. Code:${error.code}, message:${error.message}`); 2491 return; 2492 } 2493 udp.on('message', (data: Data) => { 2494 console.info("Succeeded to get data: " + JSON.stringify(data)); 2495 }); 2496 netHandle.bindSocket(udp).then(() => { 2497 console.info("bind socket success"); 2498 }).catch((error: BusinessError) => { 2499 console.error(`Failed to bind socket. Code:${error.code}, message:${error.message}`); 2500 }); 2501 }); 2502 } 2503}); 2504``` 2505 2506### getAddressesByName 2507 2508getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>\>\): void 2509 2510Obtains all IP addresses by using the network specified by **NetHandle** to resolve the host name. This API uses an asynchronous callback to return the result. 2511 2512**Atomic service API**: This API can be used in atomic services since API version 15. 2513 2514**Required permissions**: ohos.permission.INTERNET 2515 2516**System capability**: SystemCapability.Communication.NetManager.Core 2517 2518**Parameters** 2519 2520| Name | Type | Mandatory| Description | 2521| -------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | 2522| host | string | Yes | Host name to resolve. | 2523| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes | Callback used to return the result. If all IP addresses are successfully obtained, **error** is **undefined**, and **data** is the list of all obtained IP addresses. Otherwise, **error** is an error object.| 2524 2525**Error codes** 2526 2527For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 2528 2529| ID| Error Message | 2530| ------- | --------------------------------- | 2531| 201 | Permission denied. | 2532| 401 | Parameter error. | 2533| 2100001 | Invalid parameter value. | 2534| 2100002 | Failed to connect to the service. | 2535| 2100003 | System internal error. | 2536 2537**Example** 2538 2539```ts 2540import { connection } from '@kit.NetworkKit'; 2541import { BusinessError } from '@kit.BasicServicesKit'; 2542 2543connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 2544 if (netHandle.netId == 0) { 2545 // If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements. 2546 return; 2547 } 2548 let host = "xxxx"; 2549 netHandle.getAddressesByName(host, (error: BusinessError, data: connection.NetAddress[]) => { 2550 if (error) { 2551 console.error(`Failed to get addresses. Code:${error.code}, message:${error.message}`); 2552 return; 2553 } 2554 console.info("Succeeded to get data: " + JSON.stringify(data)); 2555 }); 2556}); 2557``` 2558 2559### getAddressesByName 2560 2561getAddressesByName(host: string): Promise\<Array\<NetAddress>> 2562 2563Obtains all IP addresses by using the network specified by **NetHandle** to resolve the host name. This API uses a promise to return the result. 2564 2565**Atomic service API**: This API can be used in atomic services since API version 15. 2566 2567**Required permissions**: ohos.permission.INTERNET 2568 2569**System capability**: SystemCapability.Communication.NetManager.Core 2570 2571**Parameters** 2572 2573| Name| Type | Mandatory| Description | 2574| ------ | ------ | ---- | ------------------ | 2575| host | string | Yes | Host name to resolve.| 2576 2577**Return value** 2578 2579| Type | Description | 2580| ------------------------------------------- | ----------------------------- | 2581| Promise\<Array\<[NetAddress](#netaddress)>> | Promise used to return the result.| 2582 2583**Error codes** 2584 2585For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 2586 2587| ID| Error Message | 2588| ------- | --------------------------------- | 2589| 201 | Permission denied. | 2590| 401 | Parameter error. | 2591| 2100001 | Invalid parameter value. | 2592| 2100002 | Failed to connect to the service. | 2593| 2100003 | System internal error. | 2594 2595**Example** 2596 2597```ts 2598import { connection } from '@kit.NetworkKit'; 2599 2600connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 2601 if (netHandle.netId == 0) { 2602 // If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements. 2603 return; 2604 } 2605 let host = "xxxx"; 2606 netHandle.getAddressesByName(host).then((data: connection.NetAddress[]) => { 2607 console.info("Succeeded to get data: " + JSON.stringify(data)); 2608 }); 2609}); 2610``` 2611 2612### getAddressByName 2613 2614getAddressByName(host: string, callback: AsyncCallback\<NetAddress>): void 2615 2616Obtains the first IP address by using the network specified by **NetHandle** to resolve the host name. This API uses an asynchronous callback to return the result. 2617 2618**Required permissions**: ohos.permission.INTERNET 2619 2620**System capability**: SystemCapability.Communication.NetManager.Core 2621 2622**Parameters** 2623 2624| Name | Type | Mandatory| Description | 2625| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 2626| host | string | Yes | Host name to resolve. | 2627| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. If the first IP address is obtained successfully, **error** is **undefined**, and **data** is the first obtained IP address. Otherwise, **error** is an error object.| 2628 2629**Error codes** 2630 2631For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 2632 2633| ID| Error Message | 2634| ------- | --------------------------------- | 2635| 201 | Permission denied. | 2636| 401 | Parameter error. | 2637| 2100001 | Invalid parameter value. | 2638| 2100002 | Failed to connect to the service. | 2639| 2100003 | System internal error. | 2640 2641**Example** 2642 2643```ts 2644import { connection } from '@kit.NetworkKit'; 2645import { BusinessError } from '@kit.BasicServicesKit'; 2646 2647connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 2648 if (netHandle.netId == 0) { 2649 // If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements. 2650 return; 2651 } 2652 let host = "xxxx"; 2653 netHandle.getAddressByName(host, (error: BusinessError, data: connection.NetAddress) => { 2654 if (error) { 2655 console.error(`Failed to get address. Code:${error.code}, message:${error.message}`); 2656 return; 2657 } 2658 console.info("Succeeded to get data: " + JSON.stringify(data)); 2659 }); 2660}); 2661``` 2662 2663### getAddressByName 2664 2665getAddressByName(host: string): Promise\<NetAddress> 2666 2667Obtains the first IP address by using the network specified by **NetHandle** to resolve the host name. This API uses a promise to return the result. 2668 2669**Required permissions**: ohos.permission.INTERNET 2670 2671**System capability**: SystemCapability.Communication.NetManager.Core 2672 2673**Parameters** 2674 2675| Name| Type | Mandatory| Description | 2676| ------ | ------ | ---- | ------------------ | 2677| host | string | Yes | Host name to resolve.| 2678 2679**Return value** 2680 2681| Type | Description | 2682| ----------------------------------- | ------------------------------- | 2683| Promise\<[NetAddress](#netaddress)> | Promise used to return the result.| 2684 2685**Error codes** 2686 2687For details about the error codes, see [Network Connection Management Error Codes](errorcode-net-connection.md) and [Universal Error Codes](../errorcode-universal.md). 2688 2689| ID| Error Message | 2690| ------- | --------------------------------- | 2691| 201 | Permission denied. | 2692| 401 | Parameter error. | 2693| 2100001 | Invalid parameter value. | 2694| 2100002 | Failed to connect to the service. | 2695| 2100003 | System internal error. | 2696 2697**Example** 2698 2699```ts 2700import { connection } from '@kit.NetworkKit'; 2701 2702connection.getDefaultNet().then((netHandle: connection.NetHandle) => { 2703 if (netHandle.netId == 0) { 2704 // If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements. 2705 return; 2706 } 2707 let host = "xxxx"; 2708 netHandle.getAddressByName(host).then((data: connection.NetAddress) => { 2709 console.info("Succeeded to get data: " + JSON.stringify(data)); 2710 }); 2711}); 2712``` 2713 2714## NetCap 2715 2716Defines the network capability. 2717 2718**System capability**: SystemCapability.Communication.NetManager.Core 2719 2720| Name | Value | Description | 2721| ------------------------ | ---- | ---------------------- | 2722| NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2723| NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2724| NET_CAPABILITY_INTERNET | 12 | The network is capable of Internet access but the network connectivity is not successfully verified by the network management module. This capability is configured by the network provider. Your application can determine the network connectivity by **NET_CAPABILITY_VALIDATED** and **NET_CAPABILITY_CHECKING_CONNECTIVITY**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2725| NET_CAPABILITY_NOT_VPN | 15 | The network does not use a virtual private network (VPN).<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2726| NET_CAPABILITY_VALIDATED | 16 | The network management module successfully connects to the Huawei Cloud address through this network. This capability is configured by the network management module.<br>Note: If the network management module fails to connect to the Huawei Cloud address, this flag is not available in the network capability, but this does not mean a complete loss in Internet access. Note that for a newly connected network, this value may not reflect the actual verification result as network connectivity verification is in progress. Your application can use **NET_CAPABILITY_CHECKING_CONNECTIVITY**<sup>12+</sup> to check whether network connectivity verification is in progress.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2727| NET_CAPABILITY_PORTAL<sup>12+</sup> | 17 | The network is found to have a captive portal and user login authentication is required. This capability is set by the connection management module.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 2728| NET_CAPABILITY_CHECKING_CONNECTIVITY<sup>12+</sup> | 31 | The network management module is verifying the network connectivity. This flag remains valid until the network connectivity check is complete. During this period, the value of **NET_CAPABILITY_VALIDATED** may be incorrect. After the network connectivity check is complete, this flag is cleared and your application can determine the network connectivity by checking **NET_CAPABILITY_VALIDATED**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 2729 2730## NetBearType 2731 2732Enumerates network types. 2733 2734**System capability**: SystemCapability.Communication.NetManager.Core 2735 2736| Name | Value | Description | 2737| ----------------------- | ---- | ---------- | 2738| BEARER_CELLULAR | 0 | Cellular network.<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 2739| BEARER_WIFI | 1 | Wi-Fi network.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2740| BEARER_BLUETOOTH<sup>12+</sup> | 2 | Bluetooth network.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 2741| BEARER_ETHERNET | 3 | Ethernet network.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2742| BEARER_VPN<sup>12+</sup>| 4 | VPN. | 2743 2744## HttpProxy<sup>10+</sup> 2745 2746Represents the HTTP proxy configuration. 2747 2748**System capability**: SystemCapability.Communication.NetManager.Core 2749 2750| Name | Type | Mandatory| Description | 2751| ------ | ------ | --- |------------------------- | 2752| host | string | Yes | Host name of the proxy server.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2753| port | number | Yes | Host port. The value range is \[0, 65535].<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2754| exclusionList | Array\<string\> | Yes | List of the names of hosts that do not use a proxy. Host names can be domain names, IP addresses, or wildcards. The detailed matching rules are as follows:<br>- Domain name matching:<br> - Exact match: The host name of the proxy server exactly matches any host name in the list.<br> - Partial match: The host name of the proxy server contains any host name in the list.<br>For example, if **ample.com** is set in the host name list, **ample.com**, **www.ample.com**, and **ample.com:80** are matched, and **www.example.com** and **ample.com.org** are not matched.<br>- IP address matching: The host name of the proxy server exactly matches any IP address in the list.<br>- Both the domain name and IP address are added to the list for matching.<br>- A single asterisk (*) is the only valid wildcard. If the list contains only wildcards, the wildcards match all host names; that is, the HTTP proxy is disabled. A wildcard can only be added independently. It cannot be added to the list together with other domain names or IP addresses. Otherwise, the wildcard does not take effect.<br>- Host names are case insensitive.<br>- Protocol prefixes such as **http** and **https** are ignored during matching.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2755| username<sup>12+</sup> | string | No| Name of the user who uses the proxy.| 2756| password<sup>12+</sup> | string | No| Password of the user who uses the proxy.| 2757 2758## NetSpecifier 2759 2760Provides an instance that bears data network capabilities. 2761 2762**Atomic service API**: This API can be used in atomic services since API version 11. 2763 2764**System capability**: SystemCapability.Communication.NetManager.Core 2765 2766| Name | Type | Mandatory | Description | 2767| ----------------------- | ----------------------------------- | ---- | ------------------------------------------------------------ | 2768| netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. | 2769| bearerPrivateIdentifier | string | No | Network identifier. The identifier of the cellular network is **slot0** for SIM card 1 and **slot1** for SIM card 2. Since API version 12, you can pass the registered WLAN hotspot to the API to specify the WLAN network to be activated.| 2770 2771**Example** 2772 2773```ts 2774import { connection } from '@kit.NetworkKit'; 2775import { wifiManager } from '@kit.ConnectivityKit'; 2776import { BusinessError } from '@kit.BasicServicesKit'; 2777 2778let config: wifiManager.WifiDeviceConfig = { 2779 ssid: "TEST", 2780 preSharedKey: "**********", 2781 securityType: wifiManager.WifiSecurityType.WIFI_SEC_TYPE_PSK 2782}; 2783// Obtain the network ID of the registered WLAN through wifiManager.addCandidateConfig. 2784wifiManager.addCandidateConfig(config,(error,networkId) => { 2785 let netConnectionWlan = connection.createNetConnection({ 2786 netCapabilities: { 2787 bearerTypes: [connection.NetBearType.BEARER_WIFI] 2788 }, 2789 bearerPrivateIdentifier: `${networkId}` 2790 }); 2791 netConnectionWlan.register((error: BusinessError) => { 2792 console.error(JSON.stringify(error)); 2793 }); 2794}); 2795``` 2796 2797## NetCapabilityInfo<sup>10+</sup> 2798 2799Provides an instance that bears data network capabilities. 2800 2801**Atomic service API**: This API can be used in atomic services since API version 11. 2802 2803**System capability**: SystemCapability.Communication.NetManager.Core 2804 2805| Name | Type | Mandatory | Description | 2806| ----------------------- | ------------------------------------ | ---- | ------------------------------------------------------------ | 2807| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network. | 2808| netCap | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. | 2809 2810## NetCapabilities 2811 2812Defines the network capability set. 2813 2814**System capability**: SystemCapability.Communication.NetManager.Core 2815 2816| Name | Type | Mandatory| Description | 2817| --------------------- | ---------------------------------- | --- | ------------------------ | 2818| linkUpBandwidthKbps | number | No| Uplink (device-to-network) bandwidth, in kbit/s. The value **0** indicates that the current network bandwidth cannot be evaluated.| 2819| linkDownBandwidthKbps | number | No| Downlink (network-to-device) bandwidth, in kbit/s. The value **0** indicates that the current network bandwidth cannot be evaluated.| 2820| networkCap | Array\<[NetCap](#netcap)> | No| Network capability.<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 2821| bearerTypes | Array\<[NetBearType](#netbeartype)> | Yes| Network type. The array contains only one network type.<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 2822 2823## NetConnectionPropertyInfo<sup>11+</sup> 2824 2825Defines the network connection properties. 2826 2827**System capability**: SystemCapability.Communication.NetManager.Core 2828 2829### Attributes 2830 2831| Name | Type | Mandatory| Description | 2832| -------------------- | --------------------------------------------------- | ---- |----------------------- | 2833| netHandle | [NetHandle](#nethandle) | Yes |Data network handle.| 2834| connectionProperties | [ConnectionProperties](#connectionproperties) | Yes |Network connection properties. | 2835 2836## NetBlockStatusInfo<sup>11+</sup> 2837 2838Obtains the network block status information. 2839 2840**System capability**: SystemCapability.Communication.NetManager.Core 2841 2842### Attributes 2843 2844| Name | Type | Mandatory| Description | 2845| -------------------- | ------------------------------------- | --- |--------------------------- | 2846| netHandle | [NetHandle](#nethandle) | Yes |Data network handle. | 2847| blocked | boolean | Yes |The value **true** indicates that the network is congested, and the value **false** indicates the opposite.| 2848 2849## ConnectionProperties 2850 2851Defines the network connection properties. 2852 2853**System capability**: SystemCapability.Communication.NetManager.Core 2854 2855| Name | Type | Mandatory| Description | 2856| ------------- | ----------------------------------- | ----|--------------------------------------- | 2857| interfaceName | string | Yes|Network interface card (NIC) name. | 2858| domains | string | Yes|Domain name. | 2859| linkAddresses | Array\<[LinkAddress](#linkaddress)> | Yes|Network link information. | 2860| routes | Array\<[RouteInfo](#routeinfo)> | Yes|Network route information. | 2861| dnses | Array\<[NetAddress](#netaddress)> | Yes|Network address. For details, see [NetAddress](#netaddress).| 2862| mtu | number | Yes|Maximum transmission unit (MTU). | 2863 2864## RouteInfo 2865 2866Defines network route information. 2867 2868**System capability**: SystemCapability.Communication.NetManager.Core 2869 2870| Name | Type | Mandatory| Description | 2871| -------------- | --------------------------- | --- |-------------- | 2872| interface | string | Yes|NIC name. | 2873| destination | [LinkAddress](#linkaddress) | Yes|Destination address. | 2874| gateway | [NetAddress](#netaddress) | Yes|Gateway address. | 2875| hasGateway | boolean | Yes|Whether a gateway is available. The value **true** indicates that a gateway is available, and the value **false** indicates the opposite. | 2876| isDefaultRoute | boolean | Yes|Whether the route is the default route. The value **true** indicates that the route is the default route, and the value **false** indicates the opposite.| 2877| isExcludedRoute<sup>20+</sup>| boolean | No|Whether the route is excluded. The value **true** indicates that the route is excluded, and the value **false** indicates the opposite.| 2878 2879## LinkAddress 2880 2881Defines network link information. 2882 2883**System capability**: SystemCapability.Communication.NetManager.Core 2884 2885| Name | Type | Mandatory| Description | 2886| ------------ | ------------------------- |---- |-------------------- | 2887| address | [NetAddress](#netaddress) | Yes | Link address. | 2888| prefixLength | number | Yes |Length of the link address prefix. | 2889 2890## NetAddress 2891 2892Defines a network address. 2893 2894**Atomic service API**: This API can be used in atomic services since API version 12. 2895 2896**System capability**: SystemCapability.Communication.NetManager.Core 2897 2898| Name | Type |Mandatory| Description | 2899| ------- | ------ | -- |---------------------------- | 2900| address | string | Yes|Network address. | 2901| family | number | No|Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.| 2902| port | number | No|Port number. The value range is \[0, 65535]. The default value is **0**. | 2903 2904## HttpRequest 2905 2906type HttpRequest = http.HttpRequest 2907 2908Defines an HTTP request, which can be created using [http.createHttp](js-apis-http.md#httpcreatehttp). 2909 2910**Atomic service API**: This API can be used in atomic services since API version 11. 2911 2912**System capability**: SystemCapability.Communication.NetStack 2913 2914| Type | Description | 2915| ---------------- | --------------------------- | 2916| http.HttpRequest | HTTP request task. You need to obtain an HTTP request task before calling **HttpRequest** APIs .| 2917 2918## TCPSocket 2919 2920type TCPSocket = socket.TCPSocket 2921 2922Defines a **TCPSocket** object, which can be created using [socket.constructTCPSocketInstance](js-apis-socket.md#socketconstructtcpsocketinstance7). 2923 2924**System capability**: SystemCapability.Communication.NetStack 2925 2926| Type | Description | 2927| ---------------- | --------------------------- | 2928| socket.TCPSocket | **TCPSocket** object. | 2929 2930## UDPSocket 2931 2932type UDPSocket = socket.UDPSocket 2933 2934Defines a **UDPSocket** object, which can be created using [socket.constructUDPSocketInstance](js-apis-socket.md#socketconstructudpsocketinstance). 2935 2936**System capability**: SystemCapability.Communication.NetStack 2937 2938| Type | Description | 2939| ---------------- | --------------------------- | 2940| socket.UDPSocket | **UDPSocket** object. | 2941