1# @ohos.net.vpn (VPN Management) (System API) 2 3The **vpn** module implements virtual private network (VPN) management, such as starting and stopping a VPN. 4This module is the built-in VPN function provided by the OS. It allows users to set up VPN connections through the network settings of the OS. Generally, this module provides only limited functions and is subject to strict restrictions. 5 6> **NOTE** 7> 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. 8> The APIs provided by this module are system APIs. 9 10## Modules to Import 11 12```js 13import { vpn } from '@kit.NetworkKit'; 14``` 15 16## vpn.createVpnConnection 17 18createVpnConnection(context: AbilityContext): VpnConnection 19 20Creates a VPN connection. 21 22**System API**: This is a system API. 23 24**System capability**: SystemCapability.Communication.NetManager.Vpn 25 26**Parameters** 27 28| Name | Type | Mandatory| Description | 29| ------- | -------------------------------------------------------------------------------- | ---- | ------------ | 30| context | [AbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontext) | Yes | Specified context.| 31 32**Return value** 33 34| Type | Description | 35| :------------------------------ | :---------------------- | 36| [VpnConnection](#vpnconnection) | VPN connection object.| 37 38**Error codes** 39 40For details about the error codes, see [VPN Error Codes](errorcode-net-vpn.md). 41 42| ID| Error Message | 43| --------- | ---------------- | 44| 202 | Non-system applications use system APIs. | 45| 401 | Parameter error. | 46 47**Example** 48Stage model: 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 69Defines a VPN connection object. Before calling **VpnConnection** APIs, you need to create a VPN connection object by calling [vpn.createVpnConnection](#vpncreatevpnconnection). 70 71### setUp 72 73setUp(config: VpnConfig, callback: AsyncCallback\<number\>): void 74 75Creates a VPN based on the specified configuration. This API uses an asynchronous callback to return the result. 76 77**System API**: This is a system API. 78 79**Required permissions**: ohos.permission.MANAGE_VPN 80 81**System capability**: SystemCapability.Communication.NetManager.Vpn 82 83**Parameters** 84 85| Name | Type | Mandatory| Description | 86| -------- | ----------------------- | ---- | -------------------------------------------------------------------------------------------------- | 87| config | [VpnConfig](#vpnconfig) | Yes | VPN configuration. | 88| 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.| 89 90**Error codes** 91 92For details about the error codes, see [VPN Error Codes](errorcode-net-vpn.md). 93 94| ID| Error Message | 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**Example** 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 142Creates a VPN based on the specified configuration. This API uses a promise to return the result. 143 144**System API**: This is a system API. 145 146**Required permissions**: ohos.permission.MANAGE_VPN 147 148**System capability**: SystemCapability.Communication.NetManager.Vpn 149 150**Parameters** 151 152| Name| Type | Mandatory| Description | 153| ------ | ----------------------- | ---- | ------------------------- | 154| config | [VpnConfig](#vpnconfig) | Yes | VPN configuration.| 155 156**Return value** 157 158| Type | Description | 159| ----------------- | -------------------------------------------------------------- | 160| Promise\<number\> | Promise used to return the result, which is the file descriptor of the vNIC.| 161 162**Error codes** 163 164For details about the error codes, see [VPN Error Codes](errorcode-net-vpn.md). 165 166| ID| Error Message | 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**Example** 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 215Protects 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. 216 217**System API**: This is a system API. 218 219**Required permissions**: ohos.permission.MANAGE_VPN 220 221**System capability**: SystemCapability.Communication.NetManager.Vpn 222 223**Parameters** 224 225| Name | Type | Mandatory| Description | 226| -------- | --------------------- | ---- | ----------------------------------------------------------------------------------------- | 227| socketFd | number | Yes | Socket file descriptor. It can be obtained through [getSocketFd](js-apis-socket.md#getsocketfd10).| 228| 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. | 229 230**Error codes** 231 232For details about the error codes, see [VPN Error Codes](errorcode-net-vpn.md). 233 234| ID| Error Message | 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**Example** 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 287Protects 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. 288 289**System API**: This is a system API. 290 291**Required permissions**: ohos.permission.MANAGE_VPN 292 293**System capability**: SystemCapability.Communication.NetManager.Vpn 294 295**Parameters** 296 297| Name | Type | Mandatory| Description | 298| -------- | ------ | ---- | ------------------------------------------------------------------------------------------- | 299| socketFd | number | Yes | Socket file descriptor. It can be obtained through [getSocketFd](js-apis-socket.md#getsocketfd10-1).| 300 301**Return value** 302 303| Type | Description | 304| --------------- | ----------------------------------------------------- | 305| 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.| 306 307**Error codes** 308 309For details about the error codes, see [VPN Error Codes](errorcode-net-vpn.md). 310 311| ID| Error Message | 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**Example** 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 366Destroys a VPN. This API uses an asynchronous callback to return the result. 367 368**System API**: This is a system API. 369 370**Required permissions**: ohos.permission.MANAGE_VPN 371 372**System capability**: SystemCapability.Communication.NetManager.Vpn 373 374**Parameters** 375 376| Name | Type | Mandatory| Description | 377| -------- | --------------------- | ---- | -------------------------------------------------------------- | 378| 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.| 379 380**Error codes** 381 382For details about the error codes, see [VPN Error Codes](errorcode-net-vpn.md). 383 384| ID| Error Message | 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**Example** 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 417Destroys a VPN. This API uses a promise to return the result. 418 419**System API**: This is a system API. 420 421**Required permissions**: ohos.permission.MANAGE_VPN 422 423**System capability**: SystemCapability.Communication.NetManager.Vpn 424 425**Return value** 426 427| Type | Description | 428| --------------- | ----------------------------------------------------- | 429| 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.| 430 431**Error codes** 432 433For details about the error codes, see [VPN Error Codes](errorcode-net-vpn.md). 434 435| ID| Error Message | 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**Example** 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 468Defines the VPN configuration. 469 470**System API**: This is a system API. 471 472**System capability**: SystemCapability.Communication.NetManager.Vpn 473 474| Name | Type | Mandatory| Description | 475| ------------------- | -------------------------------------------------------------- | ---- | ----------------------------------- | 476| addresses | Array\<[LinkAddress](js-apis-net-connection.md#linkaddress)\> | Yes | IP address of the vNIC. | 477| routes | Array\<[RouteInfo](js-apis-net-connection.md#routeinfo)\> | No | Route information of the vNIC. | 478| dnsAddresses | Array\<string\> | No | IP address of the DNS server. | 479| searchDomains | Array\<string\> | No | List of DNS search domains. | 480| mtu | number | No | Maximum transmission unit (MTU), in bytes. | 481| isIPv4Accepted | boolean | No | Whether IPv4 is supported. The default value is **true**. | 482| isIPv6Accepted | boolean | No | Whether IPv6 is supported. The default value is **false**. | 483| isLegacy | boolean | No | Whether the built-in VPN is supported. The default value is **false**. | 484| isBlocking | boolean | No | Whether the blocking mode is used. The default value is **false**. | 485| trustedApplications | Array\<string\> | No | List of trusted applications, which are represented by bundle names of the string type. | 486| blockedApplications | Array\<string\> | No | List of blocked applications, which are represented by bundle names of the string type. | 487