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