• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.net.vpn (VPN 管理)
2
3VPN 管理模块,支持 VPN 的启动和停止功能。
4
5> **说明:**
6> 本模块首批接口从 API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
7
8## 导入模块
9
10```js
11import vpn from "@ohos.net.vpn";
12```
13
14## vpn.createVpnConnection
15
16createVpnConnection(context: AbilityContext): VpnConnection
17
18创建一个 VPN 连接对象。
19
20**系统接口**:此接口为系统接口。
21
22**系统能力**:SystemCapability.Communication.NetManager.Vpn
23
24**参数:**
25
26| 参数名  | 类型                                                                             | 必填 | 说明         |
27| ------- | -------------------------------------------------------------------------------- | ---- | ------------ |
28| context | [AbilityContext](js-apis-inner-application-uiAbilityContext.md#uiabilitycontext) | 是   | 指定 context |
29
30**返回值:**
31
32| 类型                            | 说明                    |
33| :------------------------------ | :---------------------- |
34| [VpnConnection](#vpnconnection) | 返回一个 VPN 连接对象。 |
35
36**错误码:**
37
38以下错误码的详细介绍参见[VPN 错误码](../errorcodes/errorcode-net-vpn.md)。
39
40| 错误码 ID | 错误信息         |
41| --------- | ---------------- |
42| 202       | Non-system applications use system APIs.         |
43| 401       | Parameter error.                                 |
44
45**示例:**
46Stage 模型示例:
47
48```ts
49import vpn from '@ohos.net.vpn';
50import common from '@ohos.app.ability.common';
51
52@Entry
53@Component
54struct Index {
55  private context = getContext(this) as common.UIAbilityContext;
56  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
57  functiontest()
58  {
59    console.info("vpn createVpnConnection: " + JSON.stringify(this.VpnConnection));
60  }
61  build() {  }
62}
63```
64
65## VpnConnection
66
67VPN 连接对象。在调用 VpnConnection 的方法前,需要先通过[vpn.createVpnConnection](#vpncreatevpnconnection)创建 VPN 连接对象。
68
69### setUp
70
71setUp(config: VpnConfig, callback: AsyncCallback\<number\>): void
72
73使用 config 创建一个 vpn 网络,使用 callback 方式作为异步方法。
74
75**系统接口**:此接口为系统接口。
76
77**需要权限**:ohos.permission.MANAGE_VPN
78
79**系统能力**:SystemCapability.Communication.NetManager.Vpn
80
81**参数:**
82
83| 参数名   | 类型                    | 必填 | 说明                                                                                               |
84| -------- | ----------------------- | ---- | -------------------------------------------------------------------------------------------------- |
85| config   | [VpnConfig](#vpnconfig) | 是   | 指定 VPN 网络的配置信息。                                                                          |
86| callback | AsyncCallback\<number\> | 是   | 回调函数,当成功启动 VPN 网络时,返回虚拟网卡的文件描述符 fd, error 为 undefined,否则为错误对象。 |
87
88**错误码:**
89
90以下错误码的详细介绍参见[VPN 错误码](../errorcodes/errorcode-net-vpn.md)。
91
92| 错误码 ID | 错误信息                                         |
93| --------- | ------------------------------------------------ |
94| 201       | Permission denied.                               |
95| 202       | Non-system applications use system APIs.         |
96| 401       | Parameter error.                                 |
97| 2200001   | Invalid parameter value.                         |
98| 2200002   | Operation failed. Cannot connect to service.     |
99| 2200003   | System internal error.                           |
100| 2203001   | VPN creation denied, please check the user type. |
101| 2203002   | VPN exist already, please execute destroy first. |
102
103**示例:**
104
105```js
106import vpn from '@ohos.net.vpn';
107import common from '@ohos.app.ability.common';
108import { BusinessError } from "@ohos.base";
109
110@Entry
111@Component
112struct Index {
113  private context = getContext(this) as common.UIAbilityContext;
114  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
115  SetUp(): void {
116    let config: vpn.VpnConfig = {
117      addresses: [{
118        address: {
119          address: "10.0.0.5",
120          family: 1
121        },
122        prefixLength: 24
123      }],
124      mtu: 1400,
125      dnsAddresses: ["114.114.114.114"]
126    }
127    this.VpnConnection.setUp(config, (error: BusinessError, data: number) => {
128      console.info(JSON.stringify(error));
129      console.info("tunfd: " + JSON.stringify(data));
130    });
131  }
132  build() { }
133}
134```
135
136### setUp
137
138setUp(config: VpnConfig): Promise\<number\>
139
140使用 config 创建一个 vpn 网络,使用 Promise 方式作为异步方法。
141
142**系统接口**:此接口为系统接口。
143
144**需要权限**:ohos.permission.MANAGE_VPN
145
146**系统能力**:SystemCapability.Communication.NetManager.Vpn
147
148**参数:**
149
150| 参数名 | 类型                    | 必填 | 说明                      |
151| ------ | ----------------------- | ---- | ------------------------- |
152| config | [VpnConfig](#vpnconfig) | 是   | 指定 VPN 网络的配置信息。 |
153
154**返回值:**
155
156| 类型              | 说明                                                           |
157| ----------------- | -------------------------------------------------------------- |
158| Promise\<number\> | 以 Promise 形式返回获取结果,返回指定虚拟网卡的文件描述符 fd。 |
159
160**错误码:**
161
162以下错误码的详细介绍参见[VPN 错误码](../errorcodes/errorcode-net-vpn.md)。
163
164| 错误码 ID | 错误信息                                         |
165| --------- | ------------------------------------------------ |
166| 201       | Permission denied.                               |
167| 202       | Non-system applications use system APIs.         |
168| 401       | Parameter error.                                 |
169| 2200001   | Invalid parameter value.                         |
170| 2200002   | Operation failed. Cannot connect to service.     |
171| 2200003   | System internal error.                           |
172| 2203001   | VPN creation denied, please check the user type. |
173| 2203002   | VPN exist already, please execute destroy first. |
174
175**示例:**
176
177```js
178import vpn from '@ohos.net.vpn';
179import common from '@ohos.app.ability.common';
180import { BusinessError } from "@ohos.base";
181
182@Entry
183@Component
184struct Index {
185  private context = getContext(this) as common.UIAbilityContext;
186  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
187  SetUp(): void {
188    let config: vpn.VpnConfig = {
189      addresses: [{
190        address: {
191          address: "10.0.0.5",
192          family: 1
193        },
194        prefixLength: 24
195      }],
196      mtu: 1400,
197      dnsAddresses: ["114.114.114.114"]
198    }
199    this.VpnConnection.setUp(config).then((data: number) => {
200      console.info("setUp success, tunfd: " + JSON.stringify(data));
201    }).catch((err: BusinessError) => {
202      console.info("setUp fail" + JSON.stringify(err));
203    });
204  }
205  build() { }
206}
207```
208
209### protect
210
211protect(socketFd: number, callback: AsyncCallback\<void\>): void
212
213保护套接字不受 VPN 连接影响,通过该套接字发送的数据将直接基于物理网络收发,因此其流量不会通过 VPN 转发,使用 callback 方式作为异步方法。
214
215**系统接口**:此接口为系统接口。
216
217**需要权限**:ohos.permission.MANAGE_VPN
218
219**系统能力**:SystemCapability.Communication.NetManager.Vpn
220
221**参数:**
222
223| 参数名   | 类型                  | 必填 | 说明                                                                                      |
224| -------- | --------------------- | ---- | ----------------------------------------------------------------------------------------- |
225| socketFd | number                | 是   | 指定保护的 socketfd, 该文件描述符通过[getSocketFd](js-apis-socket.md#getsocketfd10)获取。 |
226| callback | AsyncCallback\<void\> | 是   | 回调函数,成功时,error 为 undefined,失败返回错误码错误信息。                            |
227
228**错误码:**
229
230以下错误码的详细介绍参见[VPN 错误码](../errorcodes/errorcode-net-vpn.md)。
231
232| 错误码 ID | 错误信息                                     |
233| --------- | -------------------------------------------- |
234| 201       | Permission denied.                           |
235| 202       | Non-system applications use system APIs.     |
236| 401       | Parameter error.                             |
237| 2200001   | Invalid parameter value.                     |
238| 2200002   | Operation failed. Cannot connect to service. |
239| 2200003   | System internal error.                       |
240| 2203004   | Invalid socket file descriptor.              |
241
242**示例:**
243
244```js
245import socket from "@ohos.net.socket";
246import vpn from '@ohos.net.vpn';
247import common from '@ohos.app.ability.common';
248import { BusinessError } from "@ohos.base";
249
250@Entry
251@Component
252struct Index {
253  private context = getContext(this) as common.UIAbilityContext;
254  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
255
256  Protect(): void {
257    let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
258    let ipAddress: socket.NetAddress = {
259      address: "0.0.0.0"
260    }
261    tcp.bind(ipAddress);
262    let addressConnect: socket.TCPConnectOptions = {
263      address: {
264        address: "192.168.1.11",
265        port: 8888
266      },
267      timeout: 6000
268    }
269    tcp.connect(addressConnect);
270    tcp.getSocketFd().then((tunnelfd: number) => {
271      console.info("tunenlfd: " + tunnelfd);
272      this.VpnConnection.protect(tunnelfd, (error: BusinessError) => {
273        console.info(JSON.stringify(error));
274      });
275    });
276  }
277  build() { }
278}
279```
280
281### protect
282
283protect(socketFd: number): Promise\<void\>
284
285保护套接字不受 VPN 连接影响,通过该套接字发送的数据将直接基于物理网络收发,因此其流量不会通过 VPN 转发, 使用 Promise 方式作为异步方法。
286
287**系统接口**:此接口为系统接口。
288
289**需要权限**:ohos.permission.MANAGE_VPN
290
291**系统能力**:SystemCapability.Communication.NetManager.Vpn
292
293**参数:**
294
295| 参数名   | 类型   | 必填 | 说明                                                                                        |
296| -------- | ------ | ---- | ------------------------------------------------------------------------------------------- |
297| socketFd | number | 是   | 指定保护的 socketfd, 该文件描述符通过[getSocketFd](js-apis-socket.md#getsocketfd10-1)获取。 |
298
299**返回值:**
300
301| 类型            | 说明                                                  |
302| --------------- | ----------------------------------------------------- |
303| Promise\<void\> | 以 Promise 形式返回设定结果,失败返回错误码错误信息。 |
304
305**错误码:**
306
307以下错误码的详细介绍参见[VPN 错误码](../errorcodes/errorcode-net-vpn.md)。
308
309| 错误码 ID | 错误信息                                     |
310| --------- | -------------------------------------------- |
311| 201       | Permission denied.                           |
312| 202       | Non-system applications use system APIs.     |
313| 401       | Parameter error.                             |
314| 2200001   | Invalid parameter value.                     |
315| 2200002   | Operation failed. Cannot connect to service. |
316| 2200003   | System internal error.                       |
317| 2203004   | Invalid socket file descriptor.              |
318
319**示例:**
320
321```js
322import socket from "@ohos.net.socket";
323import vpn from '@ohos.net.vpn';
324import common from '@ohos.app.ability.common';
325import { BusinessError } from "@ohos.base";
326
327@Entry
328@Component
329struct Index {
330  private context = getContext(this) as common.UIAbilityContext;
331  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
332
333  Protect(): void {
334    let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
335    let ipAddress: socket.NetAddress = {
336      address: "0.0.0.0"
337    }
338    tcp.bind(ipAddress);
339    let addressConnect: socket.TCPConnectOptions = {
340      address: {
341        address: "192.168.1.11",
342        port: 8888
343      },
344      timeout: 6000
345    }
346    tcp.connect(addressConnect);
347    tcp.getSocketFd().then((tunnelfd: number) => {
348      console.info("tunenlfd: " + tunnelfd);
349      this.VpnConnection.protect(tunnelfd).then(() => {
350        console.info("protect success.");
351      }).catch((err: BusinessError) => {
352        console.info("protect fail" + JSON.stringify(err));
353      });
354    });
355  }
356  build() { }
357}
358```
359
360### destroy
361
362destroy(callback: AsyncCallback\<void\>): void
363
364销毁启动的 VPN 网络,使用 callback 方式作为异步方法。
365
366**系统接口**:此接口为系统接口。
367
368**需要权限**:ohos.permission.MANAGE_VPN
369
370**系统能力**:SystemCapability.Communication.NetManager.Vpn
371
372**参数:**
373
374| 参数名   | 类型                  | 必填 | 说明                                                           |
375| -------- | --------------------- | ---- | -------------------------------------------------------------- |
376| callback | AsyncCallback\<void\> | 是   | 回调函数,成功时,error 为 undefined,失败返回错误码错误信息。 |
377
378**错误码:**
379
380以下错误码的详细介绍参见[VPN 错误码](../errorcodes/errorcode-net-vpn.md)。
381
382| 错误码 ID | 错误信息                                     |
383| --------- | -------------------------------------------- |
384| 201       | Permission denied.                           |
385| 202       | Non-system applications use system APIs.     |
386| 401       | Parameter error.                             |
387| 2200002   | Operation failed. Cannot connect to service. |
388| 2200003   | System internal error.                       |
389
390**示例:**
391
392```js
393import vpn from '@ohos.net.vpn';
394import common from '@ohos.app.ability.common';
395import { BusinessError } from "@ohos.base";
396
397@Entry
398@Component
399struct Index {
400  private context = getContext(this) as common.UIAbilityContext;
401  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
402  Destroy(): void {
403    this.VpnConnection.destroy((error: BusinessError) => {
404      console.info(JSON.stringify(error));
405    });
406  }
407  build() { }
408}
409```
410
411### destroy
412
413destroy(): Promise\<void\>
414
415销毁启动的 VPN 网络,使用 Promise 方式作为异步方法。
416
417**系统接口**:此接口为系统接口。
418
419**需要权限**:ohos.permission.MANAGE_VPN
420
421**系统能力**:SystemCapability.Communication.NetManager.Vpn
422
423**返回值:**
424
425| 类型            | 说明                                                  |
426| --------------- | ----------------------------------------------------- |
427| Promise\<void\> | 以 Promise 形式返回设定结果,失败返回错误码错误信息。 |
428
429**错误码:**
430
431以下错误码的详细介绍参见[VPN 错误码](../errorcodes/errorcode-net-vpn.md)。
432
433| 错误码 ID | 错误信息                                     |
434| --------- | -------------------------------------------- |
435| 201       | Permission denied.                           |
436| 202       | Non-system applications use system APIs.     |
437| 2200002   | Operation failed. Cannot connect to service. |
438| 2200003   | System internal error.                       |
439
440**示例:**
441
442```js
443import vpn from '@ohos.net.vpn';
444import common from '@ohos.app.ability.common';
445import { BusinessError } from "@ohos.base";
446
447@Entry
448@Component
449struct Index {
450  private context = getContext(this) as common.UIAbilityContext;
451  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
452  Destroy(): void {
453    this.VpnConnection.destroy().then(() => {
454      console.info("destroy success.");
455    }).catch((err: BusinessError) => {
456      console.info("destroy fail" + JSON.stringify(err));
457    });
458  }
459  build() { }
460}
461```
462
463## VpnConfig
464
465VPN 配置参数。
466
467**系统接口**:此接口为系统接口。
468
469**系统能力**:SystemCapability.Communication.NetManager.Vpn
470
471| 名称                | 类型                                                           | 必填 | 说明                                |
472| ------------------- | -------------------------------------------------------------- | ---- | ----------------------------------- |
473| addresses           | Array\<[LinkAddress](js-apis-net-connection.md#linkaddress8)\> | 是   | VPN 虚拟网卡的 IP 地址。            |
474| routes              | Array\<[RouteInfo](js-apis-net-connection.md#routeinfo8)\>     | 否   | VPN 虚拟网卡的路由信息。            |
475| dnsAddresses        | Array\<string\>                                                | 否   | DNS 服务器地址信息。                |
476| searchDomains       | Array\<string\>                                                | 否   | DNS 的搜索域列表。                  |
477| mtu                 | number                                                         | 否   | 最大传输单元 MTU 值(单位:字节)。     |
478| isIPv4Accepted      | boolean                                                        | 否   | 是否支持 IPV4, 默认值为 true。      |
479| isIPv6Accepted      | boolean                                                        | 否   | 是否支持 IPV6, 默认值为 flase。     |
480| isLegacy            | boolean                                                        | 否   | 是否支持内置 VPN, 默认值为 flase。   |
481| isBlocking          | boolean                                                        | 否   | 是否阻塞模式, 默认值为 flase。       |
482| trustedApplications | Array\<string\>                                                | 否   | 白名单信息, string 类型表示的包名。  |
483| blockedApplications | Array\<string\>                                                | 否   | 黑名单信息, string 类型表示的包名。  |
484