js-apis-net-connection.md 38.8 KB
Newer Older
S
shawn_he 已提交
1 2
# Network Connection Management

S
shawn_he 已提交
3
The network connection management module provides basic network management capabilities. 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.
S
shawn_he 已提交
4

S
shawn_he 已提交
5
> **NOTE**
S
shawn_he 已提交
6 7 8 9 10
>
> 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.

## Modules to Import

S
shawn_he 已提交
11
```js
S
shawn_he 已提交
12 13 14 15 16 17 18 19 20
import connection from '@ohos.net.connection'
```

## connection.getDefaultNet

getDefaultNet(callback: AsyncCallback\<NetHandle>): void

Obtains the default active data network. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
21
**Required permission**: ohos.permission.GET_NETWORK_INFO
S
shawn_he 已提交
22 23 24 25 26 27 28 29 30 31 32

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name  | Type                                   | Mandatory| Description      |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<[NetHandle](#nethandle)> | Yes  | Callback used to return the result.|

**Example**

S
shawn_he 已提交
33
```js
S
shawn_he 已提交
34 35 36 37 38 39 40 41 42 43 44 45
connection.getDefaultNet(function (error, netHandle) {
    console.log(JSON.stringify(error))
    console.log(JSON.stringify(netHandle))
})
```

## connection.getDefaultNet

getDefaultNet(): Promise\<NetHandle>

Obtains the default active data network. This API uses a promise to return the result.

S
shawn_he 已提交
46
**Required permission**: ohos.permission.GET_NETWORK_INFO
S
shawn_he 已提交
47 48 49

**System capability**: SystemCapability.Communication.NetManager.Core

S
shawn_he 已提交
50
**Return value**
S
shawn_he 已提交
51 52 53 54 55 56 57

| Type                             | Description                                 |
| --------------------------------- | ------------------------------------- |
| Promise\<[NetHandle](#nethandle)> | Promise used to return the result.|

**Example**

S
shawn_he 已提交
58
```js
S
shawn_he 已提交
59 60 61 62 63
connection.getDefaultNet().then(function (netHandle) {
    console.log(JSON.stringify(netHandle))
})
```

S
shawn_he 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
## connection.getDefaultNetSync

getDefaultNetSync(): NetHandle;

Obtains the default active data network in synchronous mode.

**Required permission**: ohos.permission.GET_NETWORK_INFO

**System capability**: SystemCapability.Communication.NetManager.Core

**Return value**

| Type     | Description                              |
| --------- | ---------------------------------- |
| NetHandle | Handle of the default active data network.|

**Example**

```js
let netHandle = connection.getDefaultNetSync();
```


S
shawn_he 已提交
87 88 89 90 91
## connection.hasDefaultNet

hasDefaultNet(callback: AsyncCallback\<boolean>): void

Checks whether the default data network is activated. This API uses an asynchronous callback to return the result.
S
shawn_he 已提交
92 93 94
The default network priority is as follows: Ethernet > Wi-Fi > cellular. When only one network is connected, it is treated as the default data network.

**Required permission**: ohos.permission.GET_NETWORK_INFO
S
shawn_he 已提交
95 96 97 98 99 100 101 102 103 104 105

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name  | Type                   | Mandatory| Description                                  |
| -------- | ----------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<boolean> | Yes  | Callback used to return the result. The value **true** indicates that the default data network is activated.|

**Example**

S
shawn_he 已提交
106
```js
S
shawn_he 已提交
107 108
connection.hasDefaultNet(function (error, has) {
    console.log(JSON.stringify(error))
S
shawn_he 已提交
109
    console.log('has: ' + has)
S
shawn_he 已提交
110 111 112 113 114 115 116 117
})
```

## connection.hasDefaultNet

hasDefaultNet(): Promise\<boolean>

Checks whether the default data network is activated. This API uses a promise to return the result.
S
shawn_he 已提交
118 119 120
The default network priority is as follows: Ethernet > Wi-Fi > cellular. When only one network is connected, it is treated as the default data network.

**Required permission**: ohos.permission.GET_NETWORK_INFO
S
shawn_he 已提交
121 122 123

**System capability**: SystemCapability.Communication.NetManager.Core

S
shawn_he 已提交
124
**Return value**
S
shawn_he 已提交
125 126 127 128 129 130 131

| Type             | Description                                           |
| ----------------- | ----------------------------------------------- |
| Promise\<boolean> | Promise used to return the result. The value **true** indicates that the default data network is activated.|

**Example**

S
shawn_he 已提交
132
```js
S
shawn_he 已提交
133
connection.hasDefaultNet().then(function (has) {
S
shawn_he 已提交
134
    console.log('has: ' + has)
S
shawn_he 已提交
135 136 137 138 139 140 141
})
```

## connection.getAllNets

getAllNets(callback: AsyncCallback&lt;Array&lt;NetHandle&gt;&gt;): void

S
shawn_he 已提交
142
Obtains the list of all active data networks. This API uses an asynchronous callback to return the result.
S
shawn_he 已提交
143

S
shawn_he 已提交
144
**Required permission**: ohos.permission.GET_NETWORK_INFO
S
shawn_he 已提交
145 146 147 148

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**
S
shawn_he 已提交
149

S
shawn_he 已提交
150 151 152 153 154 155
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | Yes| Callback used to return the result.|

**Example**

S
shawn_he 已提交
156
```js
S
shawn_he 已提交
157 158 159 160 161 162 163 164 165 166 167
connection.getAllNets(function (error, nets) {
    console.log(JSON.stringify(error))
    console.log(JSON.stringify(nets))
});
```


## connection.getAllNets

getAllNets(): Promise&lt;Array&lt;NetHandle&gt;&gt;

S
shawn_he 已提交
168
Obtains the list of all active data networks. This API uses a promise to return the result.
S
shawn_he 已提交
169

S
shawn_he 已提交
170
**Required permission**: ohos.permission.GET_NETWORK_INFO
S
shawn_he 已提交
171 172 173

**System capability**: SystemCapability.Communication.NetManager.Core

S
shawn_he 已提交
174 175
**Return value**

S
shawn_he 已提交
176 177 178 179 180 181
| Type| Description|
| -------- | -------- |
| Promise&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | Promise used to return the result.|

**Example**

S
shawn_he 已提交
182
```js
S
shawn_he 已提交
183 184 185 186 187 188 189 190 191
connection.getAllNets().then(function (nets) {
    console.log(JSON.stringify(nets))
});
```

## connection.getConnectionProperties

getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<ConnectionProperties>): void

S
shawn_he 已提交
192
Obtains connection properties of the network corresponding to the given network handle. This API uses an asynchronous callback to return the result.
S
shawn_he 已提交
193

S
shawn_he 已提交
194
**Required permission**: ohos.permission.GET_NETWORK_INFO
S
shawn_he 已提交
195 196 197 198 199 200 201

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name   | Type                                                        | Mandatory| Description            |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
S
shawn_he 已提交
202
| netHandle | [NetHandle](#nethandle)                                      | Yes  | Handle of the data network.|
S
shawn_he 已提交
203 204 205 206
| callback  | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | Yes  | Callback used to return the result.      |

**Example**

S
shawn_he 已提交
207
```js
S
shawn_he 已提交
208 209 210 211 212 213 214 215 216 217 218 219
connection.getDefaultNet().then(function (netHandle) {
    connection.getConnectionProperties(netHandle, function (error, info) {
        console.log(JSON.stringify(error))
        console.log(JSON.stringify(info))
    })
})
```

## connection.getConnectionProperties

getConnectionProperties(netHandle: NetHandle): Promise\<ConnectionProperties>

S
shawn_he 已提交
220
Obtains connection properties of the network corresponding to **netHandle**. This API uses a promise to return the result.
S
shawn_he 已提交
221

S
shawn_he 已提交
222
**Required permission**: ohos.permission.GET_NETWORK_INFO
S
shawn_he 已提交
223 224 225 226 227 228 229

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name   | Type                   | Mandatory| Description            |
| --------- | ----------------------- | ---- | ---------------- |
S
shawn_he 已提交
230
| netHandle | [NetHandle](#nethandle) | Yes  | Handle of the data network.|
S
shawn_he 已提交
231

S
shawn_he 已提交
232
**Return value**
S
shawn_he 已提交
233 234 235 236 237 238 239

| Type                                                   | Description                             |
| ------------------------------------------------------- | --------------------------------- |
| Promise\<[ConnectionProperties](#connectionproperties)> | Promise used to return the result.|

**Example**

S
shawn_he 已提交
240
```js
S
shawn_he 已提交
241 242 243 244 245 246 247 248 249 250 251
connection.getDefaultNet().then(function (netHandle) {
    connection.getConnectionProperties(netHandle).then(function (info) {
        console.log(JSON.stringify(info))
    })
})
```

## connection.getNetCapabilities

getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilities>): void

S
shawn_he 已提交
252
Obtains capability information of the network corresponding to **netHandle**. This API uses an asynchronous callback to return the result.
S
shawn_he 已提交
253

S
shawn_he 已提交
254
**Required permission**: ohos.permission.GET_NETWORK_INFO
S
shawn_he 已提交
255 256 257 258 259 260 261

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name   | Type                                               | Mandatory| Description            |
| --------- | --------------------------------------------------- | ---- | ---------------- |
S
shawn_he 已提交
262
| netHandle | [NetHandle](#nethandle)                             | Yes  | Handle of the data network.|
S
shawn_he 已提交
263 264 265 266
| callback  | AsyncCallback\<[NetCapabilities](#netcapabilities)> | Yes  | Callback used to return the result.      |

**Example**

S
shawn_he 已提交
267
```js
S
shawn_he 已提交
268 269 270 271 272 273 274 275 276 277 278 279
connection.getDefaultNet().then(function (netHandle) {
    connection.getNetCapabilities(netHandle, function (error, info) {
        console.log(JSON.stringify(error))
        console.log(JSON.stringify(info))
    })
})
```

## connection.getNetCapabilities

getNetCapabilities(netHandle: NetHandle): Promise\<NetCapabilities>

S
shawn_he 已提交
280
Obtains capability information of the network corresponding to **netHandle**. This API uses a promise to return the result.
S
shawn_he 已提交
281

S
shawn_he 已提交
282
**Required permission**: ohos.permission.GET_NETWORK_INFO
S
shawn_he 已提交
283 284 285 286 287 288 289

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name   | Type                   | Mandatory| Description            |
| --------- | ----------------------- | ---- | ---------------- |
S
shawn_he 已提交
290
| netHandle | [NetHandle](#nethandle) | Yes  | Handle of the data network.|
S
shawn_he 已提交
291

S
shawn_he 已提交
292
**Return value**
S
shawn_he 已提交
293 294 295 296 297 298 299

| Type                                         | Description                             |
| --------------------------------------------- | --------------------------------- |
| Promise\<[NetCapabilities](#netcapabilities)> | Promise used to return the result.|

**Example**

S
shawn_he 已提交
300
```js
S
shawn_he 已提交
301 302 303 304 305 306 307 308 309 310 311
connection.getDefaultNet().then(function (netHandle) {
    connection.getNetCapabilities(netHandle).then(function (info) {
        console.log(JSON.stringify(info))
    })
})
```

## connection.reportNetConnected

reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void

S
shawn_he 已提交
312
Reports connection of the data network. This API uses an asynchronous callback to return the result.
S
shawn_he 已提交
313

S
shawn_he 已提交
314
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
S
shawn_he 已提交
315 316 317 318

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**
S
shawn_he 已提交
319

S
shawn_he 已提交
320 321 322 323 324 325 326
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|

**Example**

S
shawn_he 已提交
327
```js
S
shawn_he 已提交
328 329 330 331 332 333 334 335 336 337 338 339
connection.getDefaultNet().then(function (netHandle) {
    connection.reportNetConnected(netHandle, function (error) {
        console.log(JSON.stringify(error))
    });
});
```


## connection.reportNetConnected

reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;

S
shawn_he 已提交
340
Reports connection of the data network. This API uses a promise to return the result.
S
shawn_he 已提交
341

S
shawn_he 已提交
342
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
S
shawn_he 已提交
343 344 345 346

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**
S
shawn_he 已提交
347

S
shawn_he 已提交
348 349 350 351
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|

S
shawn_he 已提交
352 353
**Return value**

S
shawn_he 已提交
354 355 356 357 358 359
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|

**Example**

S
shawn_he 已提交
360
```js
S
shawn_he 已提交
361 362 363 364 365 366 367 368 369 370 371 372
connection.getDefaultNet().then(function (netHandle) {
    connection.reportNetConnected(netHandle).then(function () {
        console.log(`report success`)
    });
});
```


## connection.reportNetDisconnected

reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void

S
shawn_he 已提交
373
Reports disconnection of the data network. This API uses an asynchronous callback to return the result.
S
shawn_he 已提交
374

S
shawn_he 已提交
375
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
S
shawn_he 已提交
376 377 378 379

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**
S
shawn_he 已提交
380

S
shawn_he 已提交
381 382 383 384 385 386 387
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|

**Example**

S
shawn_he 已提交
388
```js
S
shawn_he 已提交
389 390 391 392 393 394 395 396 397 398 399 400
connection.getDefaultNet().then(function (netHandle) {
    connection.reportNetDisconnected(netHandle, function (error) {
        console.log(JSON.stringify(error))
    });
});
```


## connection.reportNetDisconnected

reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;

S
shawn_he 已提交
401
Reports disconnection of the data network. This API uses a promise to return the result.
S
shawn_he 已提交
402

S
shawn_he 已提交
403
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
S
shawn_he 已提交
404 405 406 407

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**
S
shawn_he 已提交
408

S
shawn_he 已提交
409 410 411 412
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|

S
shawn_he 已提交
413 414
**Return value**

S
shawn_he 已提交
415 416 417 418 419 420
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|

**Example**

S
shawn_he 已提交
421
```js
S
shawn_he 已提交
422 423 424 425 426 427 428 429 430 431 432 433 434
connection.getDefaultNet().then(function (netHandle) {
    connection.reportNetDisconnected(netHandle).then(function () {
        console.log(`report success`)
    });
});
```

## connection.getAddressesByName

getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void

Resolves the host name by using the default network to obtain all IP addresses. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
435
**Required permission**: ohos.permission.GET_NETWORK_INFO
S
shawn_he 已提交
436 437 438 439 440 441 442

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name  | Type                                             | Mandatory| Description              |
| -------- | ------------------------------------------------- | ---- | ------------------ |
S
shawn_he 已提交
443
| host     | string                                            | Yes  | Host name to be resolved.|
S
shawn_he 已提交
444 445 446 447
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes  | Callback used to return the result.        |

**Example**

S
shawn_he 已提交
448
```js
S
shawn_he 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461
let host = "xxxx";
connection.getAddressesByName(host, function (error, addresses) {
    console.log(JSON.stringify(error))
    console.log(JSON.stringify(addresses))
})
```

## connection.getAddressesByName

getAddressesByName(host: string): Promise\<Array\<NetAddress>>

Resolves the host name by using the default network to obtain all IP addresses. This API uses a promise to return the result.

S
shawn_he 已提交
462
**Required permission**: ohos.permission.GET_NETWORK_INFO
S
shawn_he 已提交
463 464 465 466 467 468 469

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name| Type  | Mandatory| Description              |
| ------ | ------ | ---- | ------------------ |
S
shawn_he 已提交
470
| host   | string | Yes  | Host name to be resolved.|
S
shawn_he 已提交
471

S
shawn_he 已提交
472
**Return value**
S
shawn_he 已提交
473 474 475

| Type                                       | Description                         |
| ------------------------------------------- | ----------------------------- |
S
shawn_he 已提交
476
| Promise\<Array\<[NetAddress](#netaddress)>> | Promise used to return the result.|
S
shawn_he 已提交
477 478 479

**Example**

S
shawn_he 已提交
480
```js
S
shawn_he 已提交
481 482 483 484 485 486
let host = "xxxx";
connection.getAddressesByName(host).then(function (addresses) {
    console.log(JSON.stringify(addresses))
})
```

S
shawn_he 已提交
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585

## connection.enableAirplaneMode

enableAirplaneMode(callback: AsyncCallback\<void>): void

Enables the airplane mode. This API uses an asynchronous callback to return the result.

This is a system API.

**System capability**:  SystemCapability.Communication.NetManager.Core

**Parameters**

| Name  | Type                                             | Mandatory| Description              |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.        |

**Example**

```js
connection.enableAirplaneMode(function (error) {
    console.log(JSON.stringify(error))
})
```

## connection.enableAirplaneMode

enableAirplaneMode(): Promise\<void>

Enables the airplane mode. This API uses a promise to return the result.

This is a system API.

**System capability**:  SystemCapability.Communication.NetManager.Core

**Return value**

| Type                                       | Description                         |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise used to return the result.|

**Example**

```js
connection.enableAirplaneMode().then(function (error) {
    console.log(JSON.stringify(error))
})
```


## connection.disableAirplaneMode

disableAirplaneMode(callback: AsyncCallback\<void>): void

Disables the airplane mode. This API uses an asynchronous callback to return the result.

This is a system API.

**System capability**:  SystemCapability.Communication.NetManager.Core

**Parameters**

| Name  | Type                                             | Mandatory| Description              |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.        |

**Example**

```js
connection.disableAirplaneMode(function (error) {
    console.log(JSON.stringify(error))
})
```

## connection.disableAirplaneMode

disableAirplaneMode(): Promise\<void>

Disables the airplane mode. This API uses a promise to return the result.

This is a system API.

**System capability**:  SystemCapability.Communication.NetManager.Core

**Return value**

| Type                                       | Description                         |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | Promise used to return the result.|

**Example**

```js
connection.disableAirplaneMode().then(function (error) {
    console.log(JSON.stringify(error))
})
```


S
shawn_he 已提交
586 587 588 589
## connection.createNetConnection

createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection

S
shawn_he 已提交
590
Obtains the handle of the network specified by **netSpecifier**.
S
shawn_he 已提交
591 592 593 594 595 596 597 598 599 600

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name      | Type                         | Mandatory| Description                                                        |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| netSpecifier | [NetSpecifier](#netspecifier) | No  | Network specifier. If this parameter is not set, the default network is used.                  |
| timeout      | number                        | No  | Timeout interval for obtaining the network specified by **netSpecifier**. This parameter is valid only when **netSpecifier** is set.|

S
shawn_he 已提交
601
**Return value**
S
shawn_he 已提交
602 603 604 605 606 607 608

| Type                           | Description                |
| ------------------------------- | -------------------- |
| [NetConnection](#netconnection) | Handle of the network specified by **netSpecifier**.|

**Example**

S
shawn_he 已提交
609
```js
S
shawn_he 已提交
610 611 612 613 614 615
// Default network
let netConnection = connection.createNetConnection()

// Cellular network
let netConnectionCellular = connection.createNetConnection({
    netCapabilities: {
S
shawn_he 已提交
616
        bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
S
shawn_he 已提交
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
    }
})
```

## NetConnection

Represents the network connection handle.

### on('netAvailable')

on(type: 'netAvailable', callback: Callback\<NetHandle>): void

Registers a listener for **netAvailable** events.

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name  | Type                              | Mandatory| Description                                                        |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
637
| type     | string                             | Yes  | Event type. The value is fixed at **netAvailable**.<br>**netAvailable**: event indicating that the data network is available.|
S
shawn_he 已提交
638 639 640 641
| callback | Callback\<[NetHandle](#nethandle)> | Yes  | Callback used to return the result.                                                  |

**Example**

S
shawn_he 已提交
642
```js
S
shawn_he 已提交
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
netConnection.on('netAvailable', function (data) {
    console.log(JSON.stringify(data))
})
```

### on('netCapabilitiesChange')

on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void

Registers a listener for **netCapabilitiesChange** events.

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name  | Type                                                        | Mandatory| Description                                                        |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
660
| type     | string                                                       | Yes  | Event type. The value is fixed at **netCapabilitiesChange**.<br>**netCapabilitiesChange**: event indicating that network capabilities have changed.|
S
shawn_he 已提交
661 662 663 664
| callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | Yes  | Callback used to return the result.                                                  |

**Example**

S
shawn_he 已提交
665
```js
S
shawn_he 已提交
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
netConnection.on('netCapabilitiesChange', function (data) {
    console.log(JSON.stringify(data))
})
```

### on('netConnectionPropertiesChange')

on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void

Registers a listener for **netConnectionPropertiesChange** events.

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name  | Type                                                        | Mandatory| Description                                                        |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
683
| type     | string                                                       | Yes  | Event type. The value is fixed at **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.|
S
shawn_he 已提交
684 685 686 687
| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | Yes  | Callback used to return the result.                                                  |

**Example**

S
shawn_he 已提交
688
```js
S
shawn_he 已提交
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
netConnection.on('netConnectionPropertiesChange', function (data) {
    console.log(JSON.stringify(data))
})
```

### on('netBlockStatusChange')

on(type: 'netBlockStatusChange', callback: Callback&lt;{ netHandle: NetHandle, blocked: boolean }&gt;): void

Registers a listener for **netBlockStatusChange** events.

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name  | Type                                                        | Mandatory| Description                                                        |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
706
| type     | string                                                       | Yes  | Event type. The value is fixed at **netBlockStatusChange**.<br>**netBlockStatusChange**: event indicating a change in the network blocking status.|
S
shawn_he 已提交
707 708 709 710
| callback | Callback&lt;{&nbsp;netHandle:&nbsp;[NetHandle](#nethandle),&nbsp;blocked:&nbsp;boolean&nbsp;}&gt; | Yes  | Callback used to return the result.                                                  |

**Example**

S
shawn_he 已提交
711
```js
S
shawn_he 已提交
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
netConnection.on('netBlockStatusChange', function (data) {
    console.log(JSON.stringify(data))
})
```

### on('netLost')

on(type: 'netLost', callback: Callback\<NetHandle>): void

Registers a listener for **netLost** events.

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name  | Type                              | Mandatory| Description                                                        |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
729
| type     | string                             | Yes  | Event type. The value is fixed at **netLost**.<br>netLost: event indicating that the network is interrupted or normally disconnected.|
S
shawn_he 已提交
730 731 732 733
| callback | Callback\<[NetHandle](#nethandle)> | Yes  | Callback used to return the result.                                                  |

**Example**

S
shawn_he 已提交
734
```js
S
shawn_he 已提交
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
let netConnection1 = connection.createNetConnection()
netConnection1.on('netLost', function (data) {
    console.log(JSON.stringify(data))
})
```

### on('netUnavailable')

on(type: 'netUnavailable', callback: Callback\<void>): void

Registers a listener for **netUnavailable** events.

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name  | Type           | Mandatory| Description                                                        |
| -------- | --------------- | ---- | ------------------------------------------------------------ |
S
shawn_he 已提交
753
| type     | string          | Yes  | Event type. The value is fixed at **netUnavailable**.<br>**netUnavailable**: event indicating that the network is unavailable.|
S
shawn_he 已提交
754 755 756 757
| callback | Callback\<void> | Yes  | Callback used to return the result.                                                  |

**Example**

S
shawn_he 已提交
758
```js
S
shawn_he 已提交
759 760 761 762 763 764 765 766 767 768 769
netConnection.on('netUnavailable', function (data) {
    console.log(JSON.stringify(data))
})
```

### register

register(callback: AsyncCallback\<void>): void

Registers a listener for network status changes.

S
shawn_he 已提交
770
**Required permission**: ohos.permission.GET_NETWORK_INFO
S
shawn_he 已提交
771 772 773 774 775 776 777 778 779 780 781

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name  | Type                | Mandatory| Description      |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|

**Example**

S
shawn_he 已提交
782
```js
S
shawn_he 已提交
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
netConnection.register(function (error) {
    console.log(JSON.stringify(error))
})
```

### unregister

unregister(callback: AsyncCallback\<void>): void

Unregisters the listener for network status changes.

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name  | Type                | Mandatory| Description      |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|

**Example**

S
shawn_he 已提交
804
```js
S
shawn_he 已提交
805 806 807 808 809 810 811 812 813
netConnection.unregister(function (error) {
    console.log(JSON.stringify(error))
})
```

## NetHandle

Defines the handle of the data network.

S
shawn_he 已提交
814
Before invoking NetHandle APIs, call **getNetHandle** to obtain a **NetHandle** object.
S
shawn_he 已提交
815 816 817

**System capability**: SystemCapability.Communication.NetManager.Core

S
shawn_he 已提交
818
### Parameters
S
shawn_he 已提交
819 820 821

| Name| Type  | Description                     |
| ------ | ------ | ------------------------- |
S
shawn_he 已提交
822
| netId  | number | Network ID. The value must be greater than or equal to 100.|
S
shawn_he 已提交
823

S
shawn_he 已提交
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
### bindSocket

bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>): void;

Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses an asynchronous callback to return the result.

**Required permission**: ohos.permission.GET_NETWORK_INFO

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name     | Type                    | Mandatory| Description                           |
| ----------- | ------------------------ | ---- | -------------------------------|
| socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | Yes| **TCPSocket** or **UDPSocket** object.|
| callback    | AsyncCallback\<void>      | Yes  | Callback used to return the result.                       |

**Example**

```js
connection.getDefaultNet().then(function (netHandle) {
    var tcp = socket.constructTCPSocketInstance();
    var udp = socket.constructUDPSocketInstance();
    let socketType = "xxxx";
    if (socketType == "TCPSocket") {
        tcp.bind({
            address: "xxxx", port: xxxx, family: xxxx
        }, err => {
            netHandle.bindSocket(tcp, function (error, data) {
            console.log(JSON.stringify(error))
            console.log(JSON.stringify(data))
        })
    } else {
        udp.on('message', callback);
        udp.bind({
            address: "xxxx", port: xxxx, family: xxxx
        }, err => {
            udp.on('message', (data) => {
            console.log(JSON.stringify(data))
            });
            netHandle.bindSocket(udp, function (error, data) {
            console.log(JSON.stringify(error))
            console.log(JSON.stringify(data))
            });
        })
     }
}
```

### bindSocket

bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\<void>;

Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses a promise to return the result.

**Required permission**: ohos.permission.GET_NETWORK_INFO

**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name         | Type                 | Mandatory | Description                          |
| --------------- | --------------------- | ---- | ------------------------------ |
| socketParam     | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | Yes  | **TCPSocket** or **UDPSocket** object.|

**Return value**

| Type          | Description                  |
| -------------- | ---------------------- |
| Promise\<void> | Promise used to return the result.|

**Example**

```js
connection.getDefaultNet().then(function (netHandle) {
    var tcp = socket.constructTCPSocketInstance();
    var udp = socket.constructUDPSocketInstance();
    let socketType = "xxxx";
    if(socketType == "TCPSocket") {
        tcp.bind({
            address: "xxxx", port: xxxx, family: xxxx
        }, err => {
            netHandle.bindSocket(tcp).then(err, data) {
            console.log(JSON.stringify(data))
        })
    } else {
        udp.on('message', callback);
        udp.bind({
            address: "xxxx", port: xxxx, family: xxxx
        }, err => {
            udp.on('message', (data) => {
            console.log(JSON.stringify(data))
            });
            netHandle.bindSocket(tcp).then(err, data) {
            console.log(JSON.stringify(data))
            });
        })
     }
}
```


S
shawn_he 已提交
926 927 928 929 930 931
### getAddressesByName

getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void

Resolves the host name by using the corresponding network to obtain all IP addresses. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
932 933
**Required permission**: ohos.permission.GET_NETWORK_INFO

S
shawn_he 已提交
934 935 936 937 938 939
**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name  | Type                                             | Mandatory| Description              |
| -------- | ------------------------------------------------- | ---- | ------------------ |
S
shawn_he 已提交
940
| host     | string                                            | Yes  | Host name to be resolved.|
S
shawn_he 已提交
941 942 943 944
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | Yes  | Callback used to return the result.          |

**Example**

S
shawn_he 已提交
945
```js
S
shawn_he 已提交
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
connection.getDefaultNet().then(function (netHandle) {
    let host = "xxxx";
    netHandle.getAddressesByName(host, function (error, addresses) {
        console.log(JSON.stringify(error))
        console.log(JSON.stringify(addresses))
    })
})
```

### getAddressesByName

getAddressesByName(host: string): Promise\<Array\<NetAddress>>

Resolves the host name by using the corresponding network to obtain all IP addresses. This API uses a promise to return the result.

S
shawn_he 已提交
961 962
**Required permission**: ohos.permission.GET_NETWORK_INFO

S
shawn_he 已提交
963 964 965 966 967 968
**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name| Type  | Mandatory| Description              |
| ------ | ------ | ---- | ------------------ |
S
shawn_he 已提交
969
| host   | string | Yes  | Host name to be resolved.|
S
shawn_he 已提交
970

S
shawn_he 已提交
971
**Return value**
S
shawn_he 已提交
972 973 974 975 976 977 978

| Type                                       | Description                         |
| ------------------------------------------- | ----------------------------- |
| Promise\<Array\<[NetAddress](#netaddress)>> | Promise used to return the result.|

**Example**

S
shawn_he 已提交
979
```js
S
shawn_he 已提交
980 981 982 983 984 985 986 987 988 989 990 991 992 993
connection.getDefaultNet().then(function (netHandle) {
    let host = "xxxx";
    netHandle.getAddressesByName(host).then(function (addresses) {
        console.log(JSON.stringify(addresses))
    })
})
```

### getAddressByName

getAddressByName(host: string, callback: AsyncCallback\<NetAddress>): void

Resolves the host name by using the corresponding network to obtain the first IP address. This API uses an asynchronous callback to return the result.

S
shawn_he 已提交
994 995
**Required permission**: ohos.permission.GET_NETWORK_INFO

S
shawn_he 已提交
996 997 998 999 1000 1001
**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name  | Type                                     | Mandatory| Description              |
| -------- | ----------------------------------------- | ---- | ------------------ |
S
shawn_he 已提交
1002
| host     | string                                    | Yes  | Host name to be resolved.|
S
shawn_he 已提交
1003 1004 1005 1006
| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes  | Callback used to return the result.        |

**Example**

S
shawn_he 已提交
1007
```js
S
shawn_he 已提交
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
connection.getDefaultNet().then(function (netHandle) {
    let host = "xxxx";
    netHandle.getAddressByName(host, function (error, address) {
        console.log(JSON.stringify(error))
        console.log(JSON.stringify(address))
    })
})
```

### getAddressByName

getAddressByName(host: string): Promise\<NetAddress>

Resolves the host name by using the corresponding network to obtain the first IP address. This API uses a promise to return the result.

S
shawn_he 已提交
1023 1024
**Required permission**: ohos.permission.GET_NETWORK_INFO

S
shawn_he 已提交
1025 1026 1027 1028 1029 1030
**System capability**: SystemCapability.Communication.NetManager.Core

**Parameters**

| Name| Type  | Mandatory| Description              |
| ------ | ------ | ---- | ------------------ |
S
shawn_he 已提交
1031
| host   | string | Yes  | Host name to be resolved.|
S
shawn_he 已提交
1032

S
shawn_he 已提交
1033
**Return value**
S
shawn_he 已提交
1034 1035 1036 1037 1038 1039 1040

| Type                               | Description                           |
| ----------------------------------- | ------------------------------- |
| Promise\<[NetAddress](#netaddress)> | Promise used to return the result.|

**Example**

S
shawn_he 已提交
1041
```js
S
shawn_he 已提交
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
connection.getDefaultNet().then(function (netHandle) {
    let host = "xxxx";
    netHandle.getAddressByName(host).then(function (address) {
        console.log(JSON.stringify(address))
    })
})
```

## NetSpecifier

Provides an instance that bears data network capabilities.

**System capability**: SystemCapability.Communication.NetManager.Core

| Name                 | Type                               | Description                                                        |
| ----------------------- | ----------------------------------- | ------------------------------------------------------------ |
| netCapabilities         | [NetCapabilities](#netcapabilities) | Network transmission capabilities and bearer types of the data network.                          |
| bearerPrivateIdentifier | string                              | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).|

## NetCapabilities

Defines the network capability set.

**System capability**: SystemCapability.Communication.NetManager.Core

| Name               | Type                              | Description                    |
| --------------------- | ---------------------------------- | ------------------------ |
| linkUpBandwidthKbps   | number                             | Uplink (from the device to the network) bandwidth.|
| linkDownBandwidthKbps | number                             | Downlink (from the network to the device) bandwidth.|
| networkCap            | Array<[NetCap](#netcap)>           | Network capability.          |
S
shawn_he 已提交
1072
| bearerTypes           | Array<[NetBearType](#netbeartype)> | Network type.              |
S
shawn_he 已提交
1073 1074 1075 1076 1077 1078 1079

## NetCap

Defines the network capability.

**System capability**: SystemCapability.Communication.NetManager.Core

S
shawn_he 已提交
1080
| Name                 | Value  | Description                  |
S
shawn_he 已提交
1081 1082 1083
| ------------------------ | ---- | ---------------------- |
| NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.|
| NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.|
S
shawn_he 已提交
1084
| NET_CAPABILITY_INTERNET  | 12   | The network can connect to the Internet.|
S
shawn_he 已提交
1085
| NET_CAPABILITY_NOT_VPN | 15 | The network does not use a Virtual Private Network (VPN).|
S
shawn_he 已提交
1086
| NET_CAPABILITY_VALIDATED | 16   | The network is available.            |
S
shawn_he 已提交
1087 1088 1089 1090 1091 1092 1093

## NetBearType

Defines the network type.

**System capability**: SystemCapability.Communication.NetManager.Core

S
shawn_he 已提交
1094
| Name        | Value  | Description       |
S
shawn_he 已提交
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
| --------------- | ---- | ----------- |
| BEARER_CELLULAR | 0    | Cellular network |
| BEARER_WIFI     | 1    | Wi-Fi network|
| BEARER_ETHERNET | 3 | Ethernet network|

## ConnectionProperties

Defines the network connection properties.

**System capability**: SystemCapability.Communication.NetManager.Core

| Name      | Type                              | Description            |
| ------------- | ---------------------------------- | ---------------- |
| interfaceName | string                             | NIC card name.      |
| domains       | string                             | Domain. The default value is **""**.|
| linkAddresses | Array<[LinkAddress](#linkaddress)> | Link information.      |
| routes        | Array<[RouteInfo](#routeinfo)>     | Route information.      |
| dnses | Array&lt;[NetAddress](#netaddress)&gt; | Network address. For details, see [NetAddress](#netaddress).|
| mtu           | number                             | Maximum transmission unit (MTU).  |

## LinkAddress

S
shawn_he 已提交
1117
Network link information.
S
shawn_he 已提交
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127

**System capability**: SystemCapability.Communication.NetManager.Core

| Name      | Type                     | Description                |
| ------------ | ------------------------- | -------------------- |
| address      | [NetAddress](#netaddress) | Link address.          |
| prefixLength | number                    | Length of the link address prefix.|

## RouteInfo

S
shawn_he 已提交
1128
Network route information.
S
shawn_he 已提交
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149

**System capability**: SystemCapability.Communication.NetManager.Core

| Name        | Type                       | Description            |
| -------------- | --------------------------- | ---------------- |
| interface      | string                      | NIC card name.      |
| destination    | [LinkAddress](#linkaddress) | Destination IP address.      |
| gateway        | [NetAddress](#netaddress)   | Gateway address.      |
| hasGateway     | boolean                     | Whether a gateway is present.    |
| isDefaultRoute | boolean                     | Whether the route is the default route.|

## NetAddress

Defines the network address.

**System capability**: SystemCapability.Communication.NetManager.Core

| Name | Type  | Description                          |
| ------- | ------ | ------------------------------ |
| address | string | Network address.                        |
| family  | number | Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.|
S
shawn_he 已提交
1150
| port    | number | Port number. The value ranges from **0** to **65535**.   |