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 API**: This is a system API. 21 22**System capability**: SystemCapability.Communication.NetManager.Vpn 23 24**Parameters** 25 26| Name | Type | Mandatory| Description | 27| ------- | -------------------------------------------------------------------------------- | ---- | ------------ | 28| context | [AbilityContext](js-apis-inner-application-uiAbilityContext.md#uiabilitycontext) | Yes | Specified context.| 29 30**Return value** 31 32| Type | Description | 33| :------------------------------ | :---------------------- | 34| [VpnConnection](#vpnconnection) | VPN connection object.| 35 36**Error codes** 37 38For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md). 39 40| ID| Error Message | 41| --------- | ---------------- | 42| 202 | Non-system applications use system APIs. | 43| 401 | Parameter error. | 44 45**Example** 46Stage model: 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 67Defines a VPN connection object. Before calling **VpnConnection** APIs, you need to create a VPN connection object by calling [vpn.createVpnConnection](#vpncreatevpnconnection). 68 69### setUp 70 71setUp(config: VpnConfig, callback: AsyncCallback\<number\>): void 72 73Creates a VPN based on the specified configuration. This API uses an asynchronous callback to return the result. 74 75**System API**: This is a system API. 76 77**Required permissions**: ohos.permission.MANAGE_VPN 78 79**System capability**: SystemCapability.Communication.NetManager.Vpn 80 81**Parameters** 82 83| Name | Type | Mandatory| Description | 84| -------- | ----------------------- | ---- | -------------------------------------------------------------------------------------------------- | 85| config | [VpnConfig](#vpnconfig) | Yes | VPN configuration. | 86| 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.| 87 88**Error codes** 89 90For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md). 91 92| ID| Error Message | 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**Example** 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 140Creates a VPN based on the specified configuration. This API uses a promise to return the result. 141 142**System API**: This is a system API. 143 144**Required permissions**: ohos.permission.MANAGE_VPN 145 146**System capability**: SystemCapability.Communication.NetManager.Vpn 147 148**Parameters** 149 150| Name| Type | Mandatory| Description | 151| ------ | ----------------------- | ---- | ------------------------- | 152| config | [VpnConfig](#vpnconfig) | Yes | VPN configuration.| 153 154**Return value** 155 156| Type | Description | 157| ----------------- | -------------------------------------------------------------- | 158| Promise\<number\> | Promise used to return the result, which is the file descriptor of the vNIC.| 159 160**Error codes** 161 162For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md). 163 164| ID| Error Message | 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**Example** 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 213Protects 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. 214 215**System API**: This is a system API. 216 217**Required permissions**: ohos.permission.MANAGE_VPN 218 219**System capability**: SystemCapability.Communication.NetManager.Vpn 220 221**Parameters** 222 223| Name | Type | Mandatory| Description | 224| -------- | --------------------- | ---- | ----------------------------------------------------------------------------------------- | 225| socketFd | number | Yes | Socket file descriptor. It can be obtained through [getSocketFd](js-apis-socket.md#getsocketfd10).| 226| 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. | 227 228**Error codes** 229 230For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md). 231 232| ID| Error Message | 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**Example** 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 285Protects 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. 286 287**System API**: This is a system API. 288 289**Required permissions**: ohos.permission.MANAGE_VPN 290 291**System capability**: SystemCapability.Communication.NetManager.Vpn 292 293**Parameters** 294 295| Name | Type | Mandatory| Description | 296| -------- | ------ | ---- | ------------------------------------------------------------------------------------------- | 297| socketFd | number | Yes | Socket file descriptor. It can be obtained through [getSocketFd](js-apis-socket.md#getsocketfd10-1).| 298 299**Return value** 300 301| Type | Description | 302| --------------- | ----------------------------------------------------- | 303| 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.| 304 305**Error codes** 306 307For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md). 308 309| ID| Error Message | 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**Example** 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 364Destroys a VPN. This API uses an asynchronous callback to return the result. 365 366**System API**: This is a system API. 367 368**Required permissions**: ohos.permission.MANAGE_VPN 369 370**System capability**: SystemCapability.Communication.NetManager.Vpn 371 372**Parameters** 373 374| Name | Type | Mandatory| Description | 375| -------- | --------------------- | ---- | -------------------------------------------------------------- | 376| 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.| 377 378**Error codes** 379 380For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md). 381 382| ID| Error Message | 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**Example** 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 415Destroys a VPN. This API uses a promise to return the result. 416 417**System API**: This is a system API. 418 419**Required permissions**: ohos.permission.MANAGE_VPN 420 421**System capability**: SystemCapability.Communication.NetManager.Vpn 422 423**Return value** 424 425| Type | Description | 426| --------------- | ----------------------------------------------------- | 427| 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.| 428 429**Error codes** 430 431For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md). 432 433| ID| Error Message | 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**Example** 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 465Defines the VPN configuration. 466 467**System API**: This is a system API. 468 469**System capability**: SystemCapability.Communication.NetManager.Vpn 470 471| Name | Type | Mandatory| Description | 472| ------------------- | -------------------------------------------------------------- | ---- | ----------------------------------- | 473| addresses | Array\<[LinkAddress](js-apis-net-connection.md#linkaddress)\> | Yes | IP address of the vNIC. | 474| routes | Array\<[RouteInfo](js-apis-net-connection.md#routeinfo)\> | No | Route information of the vNIC. | 475| dnsAddresses | Array\<string\> | No | IP address of the DNS server. | 476| searchDomains | Array\<string\> | No | List of DNS search domains. | 477| mtu | number | No | Maximum transmission unit (MTU), in bytes. | 478| isIPv4Accepted | boolean | No | Whether IPv4 is supported. The default value is **true**. | 479| isIPv6Accepted | boolean | No | Whether IPv6 is supported. The default value is **false**. | 480| isLegacy | boolean | No | Whether the built-in VPN is supported. The default value is **false**. | 481| isBlocking | boolean | No | Whether the blocking mode is used. The default value is **false**. | 482| trustedApplications | Array\<string\> | No | List of trusted applications, which are represented by bundle names of the string type. | 483| blockedApplications | Array\<string\> | No | List of blocked applications, which are represented by bundle names of the string type. | 484