harmony 鸿蒙@ohos.net.vpn (VPN Management)

2023-10-30 浏览 (865)

@ohos.net.vpn (VPN Management)

The vpn module implements virtual private network (VPN) management, such as starting and stopping a VPN.

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.

Modules to Import

import vpn from "@ohos.net.vpn";

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 '@ohos.net.vpn';
import common from '@ohos.app.ability.common';

@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, please check the user type.
2203002VPN exist already, please execute destroy first.

Example

import vpn from '@ohos.net.vpn';
import common from '@ohos.app.ability.common';
import { BusinessError } from "@ohos.base";

@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, please check the user type.
2203002VPN exist already, please execute destroy first.

Example

import vpn from '@ohos.net.vpn';
import common from '@ohos.app.ability.common';
import { BusinessError } from "@ohos.base";

@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 from "@ohos.net.socket";
import vpn from '@ohos.net.vpn';
import common from '@ohos.app.ability.common';
import { BusinessError } from "@ohos.base";

@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 addressConnect: socket.TCPConnectOptions = {
      address: {
        address: "192.168.1.11",
        port: 8888
      },
      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 from "@ohos.net.socket";
import vpn from '@ohos.net.vpn';
import common from '@ohos.app.ability.common';
import { BusinessError } from "@ohos.base";

@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 addressConnect: socket.TCPConnectOptions = {
      address: {
        address: "192.168.1.11",
        port: 8888
      },
      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 '@ohos.net.vpn';
import common from '@ohos.app.ability.common';
import { BusinessError } from "@ohos.base";

@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.
202Non-system applications use system APIs.
2200002Operation failed. Cannot connect to service.
2200003System internal error.

Example

import vpn from '@ohos.net.vpn';
import common from '@ohos.app.ability.common';
import { BusinessError } from "@ohos.base";

@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 鸿蒙APIs

harmony 鸿蒙System Common Events (To Be Deprecated Soon)

harmony 鸿蒙System Common Events

harmony 鸿蒙API Reference Document Description

harmony 鸿蒙Enterprise Device Management Overview (for System Applications Only)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager)

harmony 鸿蒙@ohos.distributedBundle (Distributed Bundle Management)

harmony 鸿蒙@ohos.bundle (Bundle)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)

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