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