openharmony 鸿蒙 js-apis-net-vpn-sys

2025-06-12 浏览 (1)

@ohos.net.vpn (VPN Management) (System API)

The vpn module implements virtual private network (VPN) management, such as starting and stopping a VPN. This 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.

NOTE 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. The APIs provided by this module are system APIs.

Modules to Import

import { vpn } from '@kit.NetworkKit';

vpn.createVpnConnection

createVpnConnection(context: AbilityContext): VpnConnection

Creates a VPN connection.

System API: This is a system API.

System capability: SystemCapability.Communication.NetManager.Vpn

Parameters

NameTypeMandatoryDescription
contextAbilityContextYesSpecified context.

Return value

TypeDescription
VpnConnectionVPN connection object.

Error codes

For details about the error codes, see VPN Error Codes.

IDError Message
202Non-system applications use system APIs.
401Parameter error.

Example Stage model:

import { vpn } from '@kit.NetworkKit';
import { common } from '@kit.AbilityKit';

@Entry
@Component
struct Index {
  private context = getContext(this) as common.UIAbilityContext;
  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
  functiontest()
  {
    console.info("vpn createVpnConnection: " + JSON.stringify(this.VpnConnection));
  }
  build() {  }
}

VpnConnection

Defines a VPN connection object. Before calling VpnConnection APIs, you need to create a VPN connection object by calling vpn.createVpnConnection.

setUp

setUp(config: VpnConfig, callback: AsyncCallback<number>): void

Creates a VPN based on the specified configuration. This API uses an asynchronous callback to return the result.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_VPN

System capability: SystemCapability.Communication.NetManager.Vpn

Parameters

NameTypeMandatoryDescription
configVpnConfigYesVPN configuration.
callbackAsyncCallback<number>YesCallback 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.

Error codes

For details about the error codes, see VPN Error Codes.

IDError Message
201Permission denied.
202Non-system applications use system APIs.
401Parameter error.
2200001Invalid parameter value.
2200002Operation failed. Cannot connect to service.
2200003System internal error.
2203001VPN creation denied. Check the user type.
2203002VPN already exists.

Example

import { vpn } from '@kit.NetworkKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  private context = getContext(this) as common.UIAbilityContext;
  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
  SetUp(): void {
    let config: vpn.VpnConfig = {
      addresses: [{
        address: {
          address: "10.0.0.5",
          family: 1
        },
        prefixLength: 24
      }],
      mtu: 1400,
      dnsAddresses: ["114.114.114.114"]
    }
    this.VpnConnection.setUp(config, (error: BusinessError, data: number) => {
      console.info(JSON.stringify(error));
      console.info("tunfd: " + JSON.stringify(data));
    });
  }
  build() { }
}

setUp

setUp(config: VpnConfig): Promise<number>

Creates a VPN based on the specified configuration. This API uses a promise to return the result.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_VPN

System capability: SystemCapability.Communication.NetManager.Vpn

Parameters

NameTypeMandatoryDescription
configVpnConfigYesVPN configuration.

Return value

TypeDescription
Promise<number>Promise used to return the result, which is the file descriptor of the vNIC.

Error codes

For details about the error codes, see VPN Error Codes.

IDError Message
201Permission denied.
202Non-system applications use system APIs.
401Parameter error.
2200001Invalid parameter value.
2200002Operation failed. Cannot connect to service.
2200003System internal error.
2203001VPN creation denied. Check the user type.
2203002VPN already exists.

Example

import { vpn } from '@kit.NetworkKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  private context = getContext(this) as common.UIAbilityContext;
  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
  SetUp(): void {
    let config: vpn.VpnConfig = {
      addresses: [{
        address: {
          address: "10.0.0.5",
          family: 1
        },
        prefixLength: 24
      }],
      mtu: 1400,
      dnsAddresses: ["114.114.114.114"]
    }
    this.VpnConnection.setUp(config).then((data: number) => {
      console.info("setUp success, tunfd: " + JSON.stringify(data));
    }).catch((err: BusinessError) => {
      console.info("setUp fail" + JSON.stringify(err));
    });
  }
  build() { }
}

protect

protect(socketFd: number, callback: AsyncCallback<void>): void

Protects 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.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_VPN

System capability: SystemCapability.Communication.NetManager.Vpn

Parameters

NameTypeMandatoryDescription
socketFdnumberYesSocket file descriptor. It can be obtained through getSocketFd.
callbackAsyncCallback<void>YesCallback used to return the result. If the operation is successful, error is undefined. If the operation fails, an error message is returned.

Error codes

For details about the error codes, see VPN Error Codes.

IDError Message
201Permission denied.
202Non-system applications use system APIs.
401Parameter error.
2200001Invalid parameter value.
2200002Operation failed. Cannot connect to service.
2200003System internal error.
2203004Invalid socket file descriptor.

Example

import { socket, vpn } from '@kit.NetworkKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  private context = getContext(this) as common.UIAbilityContext;
  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);

  Protect(): void {
    let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
    let ipAddress: socket.NetAddress = {
      address: "0.0.0.0"
    }
    tcp.bind(ipAddress);
    let netAddress: socket.NetAddress = {
      address: "192.168.1.11",
      port: 8888
    }
    let addressConnect: socket.TCPConnectOptions = {
      address: netAddress,
      timeout: 6000
    }
    tcp.connect(addressConnect);
    tcp.getSocketFd().then((tunnelfd: number) => {
      console.info("tunenlfd: " + tunnelfd);
      this.VpnConnection.protect(tunnelfd, (error: BusinessError) => {
        console.info(JSON.stringify(error));
      });
    });
  }
  build() { }
}

protect

protect(socketFd: number): Promise<void>

Protects 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.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_VPN

System capability: SystemCapability.Communication.NetManager.Vpn

Parameters

NameTypeMandatoryDescription
socketFdnumberYesSocket file descriptor. It can be obtained through getSocketFd.

Return value

TypeDescription
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.

Error codes

For details about the error codes, see VPN Error Codes.

IDError Message
201Permission denied.
202Non-system applications use system APIs.
401Parameter error.
2200001Invalid parameter value.
2200002Operation failed. Cannot connect to service.
2200003System internal error.
2203004Invalid socket file descriptor.

Example

import { socket, vpn } from '@kit.NetworkKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  private context = getContext(this) as common.UIAbilityContext;
  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);

  Protect(): void {
    let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
    let ipAddress: socket.NetAddress = {
      address: "0.0.0.0"
    }
    tcp.bind(ipAddress);
    let netAddress: socket.NetAddress = {
      address: "192.168.1.11",
      port: 8888
    }
    let addressConnect: socket.TCPConnectOptions = {
      address: netAddress,
      timeout: 6000
    }
    tcp.connect(addressConnect);
    tcp.getSocketFd().then((tunnelfd: number) => {
      console.info("tunenlfd: " + tunnelfd);
      this.VpnConnection.protect(tunnelfd).then(() => {
        console.info("protect success.");
      }).catch((err: BusinessError) => {
        console.info("protect fail" + JSON.stringify(err));
      });
    });
  }
  build() { }
}

destroy

destroy(callback: AsyncCallback<void>): void

Destroys a VPN. This API uses an asynchronous callback to return the result.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_VPN

System capability: SystemCapability.Communication.NetManager.Vpn

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result. If the operation is successful, error is undefined. If the operation fails, an error message is returned.

Error codes

For details about the error codes, see VPN Error Codes.

IDError Message
201Permission denied.
202Non-system applications use system APIs.
401Parameter error.
2200002Operation failed. Cannot connect to service.
2200003System internal error.

Example

import { vpn } from '@kit.NetworkKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  private context = getContext(this) as common.UIAbilityContext;
  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
  Destroy(): void {
    this.VpnConnection.destroy((error: BusinessError) => {
      console.info(JSON.stringify(error));
    });
  }
  build() { }
}

destroy

destroy(): Promise<void>

Destroys a VPN. This API uses a promise to return the result.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_VPN

System capability: SystemCapability.Communication.NetManager.Vpn

Return value

TypeDescription
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.

Error codes

For details about the error codes, see VPN Error Codes.

IDError Message
201Permission denied.
401Parameter error.
202Non-system applications use system APIs.
2200002Operation failed. Cannot connect to service.
2200003System internal error.

Example

import { vpn } from '@kit.NetworkKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  private context = getContext(this) as common.UIAbilityContext;
  private VpnConnection: vpn.VpnConnection = vpn.createVpnConnection(this.context);
  Destroy(): void {
    this.VpnConnection.destroy().then(() => {
      console.info("destroy success.");
    }).catch((err: BusinessError) => {
      console.info("destroy fail" + JSON.stringify(err));
    });
  }
  build() { }
}

VpnConfig

Defines the VPN configuration.

System API: This is a system API.

System capability: SystemCapability.Communication.NetManager.Vpn

NameTypeMandatoryDescription
addressesArray<LinkAddress>YesIP address of the vNIC.
routesArray<RouteInfo>NoRoute information of the vNIC.
dnsAddressesArray<string>NoIP address of the DNS server.
searchDomainsArray<string>NoList of DNS search domains.
mtunumberNoMaximum transmission unit (MTU), in bytes.
isIPv4AcceptedbooleanNoWhether IPv4 is supported. The default value is true.
isIPv6AcceptedbooleanNoWhether IPv6 is supported. The default value is false.
isLegacybooleanNoWhether the built-in VPN is supported. The default value is false.
isBlockingbooleanNoWhether the blocking mode is used. The default value is false.
trustedApplicationsArray<string>NoList of trusted applications, which are represented by bundle names of the string type.
blockedApplicationsArray<string>NoList of blocked applications, which are represented by bundle names of the string type.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Network Kit

harmony 鸿蒙NetConn_ConnectionProperties

harmony 鸿蒙NetConn_HttpProxy

harmony 鸿蒙NetConn_NetAddr

harmony 鸿蒙NetConn_NetCapabilities

harmony 鸿蒙NetConn_NetConnCallback

harmony 鸿蒙NetConn_NetHandle

harmony 鸿蒙NetConn_NetHandleList

harmony 鸿蒙NetConn_NetSpecifier

harmony 鸿蒙NetConn_Route

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/YSUSEd