• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.net.vpn (VPN Management)
2
3The **vpn** module implements virtual private network (VPN) management, such as starting and stopping a VPN.
4
5> **NOTE**
6> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
7
8## Modules to Import
9
10```js
11import vpn from "@ohos.net.vpn";
12```
13
14## vpn.createVpnConnection
15
16createVpnConnection(context: AbilityContext): VpnConnection
17
18Creates a VPN connection.
19
20**System capability**: SystemCapability.Communication.NetManager.Vpn
21
22**Parameters**
23
24| Name | Type                                                                            | Mandatory| Description        |
25| ------- | -------------------------------------------------------------------------------- | ---- | ------------ |
26| context | [AbilityContext](js-apis-inner-application-uiAbilityContext.md#uiabilitycontext) | Yes  | Specified context.|
27
28**Return value**
29
30| Type                           | Description                   |
31| :------------------------------ | :---------------------- |
32| [VpnConnection](#vpnconnection) | VPN connection object.|
33
34**Error codes**
35
36For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
37
38| ID| Error Message        |
39| --------- | ---------------- |
40| 401       | Parameter error. |
41
42**Example**
43Stage model:
44
45```ts
46import vpn from '@ohos.net.vpn';
47import common from '@ohos.app.ability.common';
48
49@Entry
50@Component
51struct Index {
52  private context = getContext(this) as common.UIAbilityContext;
53  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
54  functiontest()
55  {
56    console.info("vpn createVpnConnection: " + JSON.stringify(this.VpnConnection));
57  }
58  build() {  }
59}
60```
61
62## VpnConnection
63
64Defines a VPN connection object. Before calling **VpnConnection** APIs, you need to create a VPN connection object by calling [vpn.createVpnConnection](#vpncreatevpnconnection).
65
66### setUp
67
68setUp(config: VpnConfig, callback: AsyncCallback\<number\>): void
69
70Creates a VPN based on the specified configuration. This API uses an asynchronous callback to return the result.
71
72**System API**: This is a system API.
73
74**Required permissions**: ohos.permission.MANAGE_VPN
75
76**System capability**: SystemCapability.Communication.NetManager.Vpn
77
78**Parameters**
79
80| Name  | Type                   | Mandatory| Description                                                                                              |
81| -------- | ----------------------- | ---- | -------------------------------------------------------------------------------------------------- |
82| config   | [VpnConfig](#vpnconfig) | Yes  | VPN configuration.                                                                         |
83| callback | AsyncCallback\<number\> | Yes  | Callback used to return the result. If a VPN is created successfully, **error** is **undefined** and **data** is the file descriptor of the vNIC. Otherwise, **error** is an error object.|
84
85**Error codes**
86
87For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
88
89| ID| Error Message                                        |
90| --------- | ------------------------------------------------ |
91| 201       | Permission denied.                               |
92| 202       | Non-system applications use system APIs.         |
93| 401       | Parameter error.                                 |
94| 2200001   | Invalid parameter value.                         |
95| 2200002   | Operation failed. Cannot connect to service.     |
96| 2200003   | System internal error.                           |
97| 2203001   | VPN creation denied, please check the user type. |
98| 2203002   | VPN exist already, please execute destroy first. |
99
100**Example**
101
102```js
103import vpn from '@ohos.net.vpn';
104import common from '@ohos.app.ability.common';
105import { BusinessError } from "@ohos.base";
106
107@Entry
108@Component
109struct Index {
110  private context = getContext(this) as common.UIAbilityContext;
111  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
112  SetUp(): void {
113    let config: vpn.VpnConfig = {
114      addresses: [{
115        address: {
116          address: "10.0.0.5",
117          family: 1
118        },
119        prefixLength: 24
120      }],
121      mtu: 1400,
122      dnsAddresses: ["114.114.114.114"]
123    }
124    this.VpnConnection.setUp(config, (error: BusinessError, data: number) => {
125      console.info(JSON.stringify(error));
126      console.info("tunfd: " + JSON.stringify(data));
127    });
128  }
129  build() { }
130}
131```
132
133### setUp
134
135setUp(config: VpnConfig): Promise\<number\>
136
137Creates a VPN based on the specified configuration. This API uses a promise to return the result.
138
139**System API**: This is a system API.
140
141**Required permissions**: ohos.permission.MANAGE_VPN
142
143**System capability**: SystemCapability.Communication.NetManager.Vpn
144
145**Parameters**
146
147| Name| Type                   | Mandatory| Description                     |
148| ------ | ----------------------- | ---- | ------------------------- |
149| config | [VpnConfig](#vpnconfig) | Yes  | VPN configuration.|
150
151**Return value**
152
153| Type             | Description                                                          |
154| ----------------- | -------------------------------------------------------------- |
155| Promise\<number\> | Promise used to return the result, which is the file descriptor of the vNIC.|
156
157**Error codes**
158
159For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
160
161| ID| Error Message                                        |
162| --------- | ------------------------------------------------ |
163| 201       | Permission denied.                               |
164| 202       | Non-system applications use system APIs.         |
165| 401       | Parameter error.                                 |
166| 2200001   | Invalid parameter value.                         |
167| 2200002   | Operation failed. Cannot connect to service.     |
168| 2200003   | System internal error.                           |
169| 2203001   | VPN creation denied, please check the user type. |
170| 2203002   | VPN exist already, please execute destroy first. |
171
172**Example**
173
174```js
175import vpn from '@ohos.net.vpn';
176import common from '@ohos.app.ability.common';
177import { BusinessError } from "@ohos.base";
178
179@Entry
180@Component
181struct Index {
182  private context = getContext(this) as common.UIAbilityContext;
183  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
184  SetUp(): void {
185    let config: vpn.VpnConfig = {
186      addresses: [{
187        address: {
188          address: "10.0.0.5",
189          family: 1
190        },
191        prefixLength: 24
192      }],
193      mtu: 1400,
194      dnsAddresses: ["114.114.114.114"]
195    }
196    this.VpnConnection.setUp(config).then((data: number) => {
197      console.info("setUp success, tunfd: " + JSON.stringify(data));
198    }).catch((err: BusinessError) => {
199      console.info("setUp fail" + JSON.stringify(err));
200    });
201  }
202  build() { }
203}
204```
205
206### protect
207
208protect(socketFd: number, callback: AsyncCallback\<void\>): void
209
210Protects sockets against a VPN connection. The data sent through sockets is directly transmitted over the physical network and therefore the traffic does not traverse through the VPN. This API uses an asynchronous callback to return the result.
211
212**System API**: This is a system API.
213
214**Required permissions**: ohos.permission.MANAGE_VPN
215
216**System capability**: SystemCapability.Communication.NetManager.Vpn
217
218**Parameters**
219
220| Name  | Type                 | Mandatory| Description                                                                                     |
221| -------- | --------------------- | ---- | ----------------------------------------------------------------------------------------- |
222| socketFd | number                | Yes  | Socket file descriptor. It can be obtained through [getSocketFd](js-apis-socket.md#getsocketfd10).|
223| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result. If the operation is successful, **error** is **undefined**. If the operation fails, an error message is returned.                           |
224
225**Error codes**
226
227For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
228
229| ID| Error Message                                    |
230| --------- | -------------------------------------------- |
231| 201       | Permission denied.                           |
232| 202       | Non-system applications use system APIs.     |
233| 401       | Parameter error.                             |
234| 2200001   | Invalid parameter value.                     |
235| 2200002   | Operation failed. Cannot connect to service. |
236| 2200003   | System internal error.                       |
237| 2203004   | Invalid socket file descriptor.              |
238
239**Example**
240
241```js
242import socket from "@ohos.net.socket";
243import vpn from '@ohos.net.vpn';
244import common from '@ohos.app.ability.common';
245import { BusinessError } from "@ohos.base";
246
247@Entry
248@Component
249struct Index {
250  private context = getContext(this) as common.UIAbilityContext;
251  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
252
253  Protect(): void {
254    let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
255    let ipAddress: socket.NetAddress = {
256      address: "0.0.0.0"
257    }
258    tcp.bind(ipAddress);
259    let addressConnect: socket.TCPConnectOptions = {
260      address: {
261        address: "192.168.1.11",
262        port: 8888
263      },
264      timeout: 6000
265    }
266    tcp.connect(addressConnect);
267    tcp.getSocketFd().then((tunnelfd: number) => {
268      console.info("tunenlfd: " + tunnelfd);
269      this.VpnConnection.protect(tunnelfd, (error: BusinessError) => {
270        console.info(JSON.stringify(error));
271      });
272    });
273  }
274  build() { }
275}
276```
277
278### protect
279
280protect(socketFd: number): Promise\<void\>
281
282Protects sockets against a VPN connection. The data sent through sockets is directly transmitted over the physical network and therefore the traffic does not traverse through the VPN. This API uses a promise to return the result.
283
284**System API**: This is a system API.
285
286**Required permissions**: ohos.permission.MANAGE_VPN
287
288**System capability**: SystemCapability.Communication.NetManager.Vpn
289
290**Parameters**
291
292| Name  | Type  | Mandatory| Description                                                                                       |
293| -------- | ------ | ---- | ------------------------------------------------------------------------------------------- |
294| socketFd | number | Yes  | Socket file descriptor. It can be obtained through [getSocketFd](js-apis-socket.md#getsocketfd10-1).|
295
296**Return value**
297
298| Type           | Description                                                 |
299| --------------- | ----------------------------------------------------- |
300| Promise\<void\> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
301
302**Error codes**
303
304For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
305
306| ID| Error Message                                    |
307| --------- | -------------------------------------------- |
308| 201       | Permission denied.                           |
309| 202       | Non-system applications use system APIs.     |
310| 401       | Parameter error.                             |
311| 2200001   | Invalid parameter value.                     |
312| 2200002   | Operation failed. Cannot connect to service. |
313| 2200003   | System internal error.                       |
314| 2203004   | Invalid socket file descriptor.              |
315
316**Example**
317
318```js
319import socket from "@ohos.net.socket";
320import vpn from '@ohos.net.vpn';
321import common from '@ohos.app.ability.common';
322import { BusinessError } from "@ohos.base";
323
324@Entry
325@Component
326struct Index {
327  private context = getContext(this) as common.UIAbilityContext;
328  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
329
330  Protect(): void {
331    let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
332    let ipAddress: socket.NetAddress = {
333      address: "0.0.0.0"
334    }
335    tcp.bind(ipAddress);
336    let addressConnect: socket.TCPConnectOptions = {
337      address: {
338        address: "192.168.1.11",
339        port: 8888
340      },
341      timeout: 6000
342    }
343    tcp.connect(addressConnect);
344    tcp.getSocketFd().then((tunnelfd: number) => {
345      console.info("tunenlfd: " + tunnelfd);
346      this.VpnConnection.protect(tunnelfd).then(() => {
347        console.info("protect success.");
348      }).catch((err: BusinessError) => {
349        console.info("protect fail" + JSON.stringify(err));
350      });
351    });
352  }
353  build() { }
354}
355```
356
357### destroy
358
359destroy(callback: AsyncCallback\<void\>): void
360
361Destroys a VPN. This API uses an asynchronous callback to return the result.
362
363**System API**: This is a system API.
364
365**Required permissions**: ohos.permission.MANAGE_VPN
366
367**System capability**: SystemCapability.Communication.NetManager.Vpn
368
369**Parameters**
370
371| Name  | Type                 | Mandatory| Description                                                          |
372| -------- | --------------------- | ---- | -------------------------------------------------------------- |
373| callback | AsyncCallback\<void\> | Yes  | Callback used to return the result. If the operation is successful, **error** is **undefined**. If the operation fails, an error message is returned.|
374
375**Error codes**
376
377For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
378
379| ID| Error Message                                    |
380| --------- | -------------------------------------------- |
381| 201       | Permission denied.                           |
382| 202       | Non-system applications use system APIs.     |
383| 401       | Parameter error.                             |
384| 2200002   | Operation failed. Cannot connect to service. |
385| 2200003   | System internal error.                       |
386
387**Example**
388
389```js
390import vpn from '@ohos.net.vpn';
391import common from '@ohos.app.ability.common';
392import { BusinessError } from "@ohos.base";
393
394@Entry
395@Component
396struct Index {
397  private context = getContext(this) as common.UIAbilityContext;
398  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
399  Destroy(): void {
400    this.VpnConnection.destroy((error: BusinessError) => {
401      console.info(JSON.stringify(error));
402    });
403  }
404  build() { }
405}
406```
407
408### destroy
409
410destroy(): Promise\<void\>
411
412Destroys a VPN. This API uses a promise to return the result.
413
414**System API**: This is a system API.
415
416**Required permissions**: ohos.permission.MANAGE_VPN
417
418**System capability**: SystemCapability.Communication.NetManager.Vpn
419
420**Return value**
421
422| Type           | Description                                                 |
423| --------------- | ----------------------------------------------------- |
424| Promise\<void\> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
425
426**Error codes**
427
428For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
429
430| ID| Error Message                                    |
431| --------- | -------------------------------------------- |
432| 201       | Permission denied.                           |
433| 202       | Non-system applications use system APIs.     |
434| 2200002   | Operation failed. Cannot connect to service. |
435| 2200003   | System internal error.                       |
436
437**Example**
438
439```js
440import vpn from '@ohos.net.vpn';
441import common from '@ohos.app.ability.common';
442import { BusinessError } from "@ohos.base";
443
444@Entry
445@Component
446struct Index {
447  private context = getContext(this) as common.UIAbilityContext;
448  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
449  Destroy(): void {
450    this.VpnConnection.destroy().then(() => {
451      console.info("destroy success.");
452    }).catch((err: BusinessError) => {
453      console.info("destroy fail" + JSON.stringify(err));
454    });
455  }
456  build() { }
457}
458```
459
460## VpnConfig
461
462Defines the VPN configuration.
463
464**System API**: This is a system API.
465
466**System capability**: SystemCapability.Communication.NetManager.Vpn
467
468| Name               | Type                                                          | Mandatory| Description                               |
469| ------------------- | -------------------------------------------------------------- | ---- | ----------------------------------- |
470| addresses           | Array\<[LinkAddress](js-apis-net-connection.md#linkaddress8)\> | Yes  | IP address of the vNIC.           |
471| routes              | Array\<[RouteInfo](js-apis-net-connection.md#routeinfo8)\>     | No  | Route information of the vNIC.           |
472| dnsAddresses        | Array\<string\>                                                | No  | IP address of the DNS server.               |
473| searchDomains       | Array\<string\>                                                | No  | List of DNS search domains.                 |
474| mtu                 | number                                                         | No  | Maximum transmission unit (MTU), in bytes.    |
475| isIPv4Accepted      | boolean                                                        | No  | Whether IPv4 is supported. The default value is **true**.     |
476| isIPv6Accepted      | boolean                                                        | No  | Whether IPv6 is supported. The default value is **false**.    |
477| isLegacy            | boolean                                                        | No  | Whether the built-in VPN is supported. The default value is **false**.  |
478| isBlocking          | boolean                                                        | No  | Whether the blocking mode is used. The default value is **false**.      |
479| trustedApplications | Array\<string\>                                                | No  | List of trusted applications, which are represented by bundle names of the string type. |
480| blockedApplications | Array\<string\>                                                | No  | List of blocked applications, which are represented by bundle names of the string type. |
481