提交 9437aa00 编写于 作者: S shawn_he

update doc

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
上级 ec362a5c
......@@ -9,6 +9,7 @@
- [Ethernet Connection](net-ethernet.md)
- [Network Connection Management](net-connection-manager.md)
- [mDNS Management](net-mdns.md)
- [VPN Management](net-vpn.md)
- IPC & RPC
- [IPC & RPC Overview](ipc-rpc-overview.md)
- [IPC & RPC Development](ipc-rpc-development-guideline.md)
......
......@@ -107,7 +107,7 @@ conn.on('netAvailable', (data => {
// Listen to network status change events. If the network is unavailable, an on_netUnavailable event is returned.
conn.on('netUnavailable', (data => {
console.log("net is unavailable, netId is " + data.netId);
console.log("net is unavailable, data is " + JSON.stringify(data));
}));
// Register an observer for network status changes.
......
# VPN Management
## Overview
A virtual private network (VPN) is a dedicated network established on a public network. On a VPN, the connection between any two nodes does not have an end-to-end physical link required by the traditional private network. Instead, user data is transmitted over a logical link because a VPN is a logical network deployed over the network platform (such as the Internet) provided by the public network service provider.
> **NOTE**
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [Traffic Management](../reference/apis/js-apis-net-vpn.md).
The following describes the development procedure specific to each application scenario.
## Available APIs
For the complete list of APIs and example code, see [VPN Management](../reference/apis/js-apis-net-vpn.md).
| Type| API| Description|
| ---- | ---- | ---- |
| ohos.net.vpn | setUp(config: VpnConfig, callback: AsyncCallback\<number\>): void | Establishes a VPN. This API uses an asynchronous callback to return the result.|
| ohos.net.vpn | protect(socketFd: number, callback: AsyncCallback\<void\>): void | Enables VPN tunnel protection. This API uses an asynchronous callback to return the result.|
| ohos.net.vpn | destroy(callback: AsyncCallback\<void\>): void | Destroys a VPN. This API uses an asynchronous callback to return the result.|
## Starting a VPN
1. Establish a VPN tunnel. The following uses the UDP tunnel as an example.
2. Enable protection for the UDP tunnel.
3. Establish a VPN.
4. Process data of the virtual network interface card (vNIC), such as reading or writing data.
5. Destroy the VPN.
This example shows how to develop an application using native C++ code. For details, see [Simple Native C++ Example (ArkTS) (API9)] (https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/NativeTemplateDemo).
The sample application consists of two parts: JS code and C++ code.
## JS Code
The JS code is used to implement the service logic, such as creating a tunnel, establishing a VPN, enabling VPN protection, and destroying a VPN.
```js
import hilog from '@ohos.hilog';
import vpn from '@ohos.net.vpn';
import UIAbility from '@ohos.app.ability.UIAbility';
import vpn_client from "libvpn_client.so"
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
globalThis.context = this.context;
}
}
let TunnelFd = -1
let VpnConnection = vpn.createVpnConnection(globalThis.context)
@Entry
@Component
struct Index {
@State message: string = 'Test VPN'
//1. Establish a VPN tunnel. The following uses the UDP tunnel as an example.
CreateTunnel() {
TunnelFd = vpn_client.udpConnect("192.168.43.208", 8888)
}
// 2. Enable protection for the UDP tunnel.
Protect() {
VpnConnection.protect(TunnelFd).then(function () {
console.info("vpn Protect Success.")
}).catch(function (err) {
console.info("vpn Protect Failed " + JSON.stringify(err))
})
}
SetupVpn() {
let config = {
addresses: [{
address: {
address: "10.0.0.5",
family: 1
},
prefixLength: 24,
}],
routes: [],
mtu: 1400,
dnsAddresses: [
"114.114.114.114"
],
acceptedApplications: [],
refusedApplications: []
}
try {
// 3. Create a VPN.
VpnConnection.setUp(config, (error, data) => {
console.info("tunfd: " + JSON.stringify(data));
// 4. Process data of the virtual vNIC, such as reading or writing data.
vpn_client.startVpn(data, TunnelFd)
})
} catch (error) {
console.info("vpn setUp fail " + JSON.stringify(error));
}
}
// 5. Destroy the VPN.
Destroy() {
vpn_client.stopVpn(TunnelFd)
VpnConnection.destroy().then(function () {
console.info("vpn Destroy Success.")
}).catch(function (err) {
console.info("vpn Destroy Failed " + JSON.stringify(err))
})
}
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
console.info("vpn Client")
})
Button('CreateTunnel').onClick(() => {
this.CreateTunnel()
}).fontSize(50)
Button('Protect').onClick(() => {
this.Protect()
}).fontSize(50)
Button('SetupVpn').onClick(() => {
this.SetupVpn()
}).fontSize(50)
Button('Destroy').onClick(() => {
this.Destroy()
}).fontSize(50)
}
.width('100%')
}
.height('100%')
}
}
```
## C++ Code
The C++ code is used for underlying service implementation, such as UDP tunnel client implementation and vNIC data read and write.
```c++
#include "napi/native_api.h"
#include "hilog/log.h"
#include <cstring>
#include <thread>
#include <js_native_api.h>
#include <js_native_api_types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <thread>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUFFER_SIZE 2048
#define VPN_LOG_TAG "NetMgrVpn"
#define VPN_LOG_DOMAIN 0x15b0
#define MAKE_FILE_NAME (strrchr(__FILE__, '/') + 1)
#define NETMANAGER_VPN_LOGE(fmt, ...) \
OH_LOG_Print(LOG_APP, LOG_ERROR, VPN_LOG_DOMAIN, VPN_LOG_TAG, "vpn [%{public}s %{public}d] " fmt, MAKE_FILE_NAME, \
__LINE__, ##__VA_ARGS__)
#define NETMANAGER_VPN_LOGI(fmt, ...) \
OH_LOG_Print(LOG_APP, LOG_INFO, VPN_LOG_DOMAIN, VPN_LOG_TAG, "vpn [%{public}s %{public}d] " fmt, MAKE_FILE_NAME, \
__LINE__, ##__VA_ARGS__)
#define NETMANAGER_VPN_LOGD(fmt, ...) \
OH_LOG_Print(LOG_APP, LOG_DEBUG, VPN_LOG_DOMAIN, VPN_LOG_TAG, "vpn [%{public}s %{public}d] " fmt, MAKE_FILE_NAME, \
__LINE__, ##__VA_ARGS__)
struct FdInfo {
int32_t tunFd = 0;
int32_t tunnelFd = 0;
struct sockaddr_in serverAddr;
};
static FdInfo fdInfo;
static bool threadRunF = false;
static std::thread threadt1;
static std::thread threadt2;
// Obtain the IP address of the UDP server.
static constexpr const int MAX_STRING_LENGTH = 1024;
std::string GetStringFromValueUtf8(napi_env env, napi_value value) {
std::string result;
char str[MAX_STRING_LENGTH] = {0};
size_t length = 0;
napi_get_value_string_utf8(env, value, str, MAX_STRING_LENGTH, &length);
if (length > 0) {
return result.append(str, length);
}
return result;
}
void HandleReadTunfd(FdInfo fdInfo) {
uint8_t buffer[BUFFER_SIZE] = {0};
while (threadRunF) {
int ret = read(fdInfo.tunFd, buffer, sizeof(buffer));
if (ret <= 0) {
if (errno != 11) {
NETMANAGER_VPN_LOGE("read tun device error: %{public}d, tunfd: %{public}d", errno, fdInfo.tunFd);
}
continue;
}
// Read data from the vNIC and send the data to the UDP server through the UDP tunnel.
NETMANAGER_VPN_LOGD("buffer: %{public}s, len: %{public}d", buffer, ret);
ret = sendto(fdInfo.tunnelFd, buffer, ret, 0, (struct sockaddr *)&fdInfo.serverAddr, sizeof(fdInfo.serverAddr));
if (ret <= 0) {
NETMANAGER_VPN_LOGE("send to server[%{public}s:%{public}d] failed, ret: %{public}d, error: %{public}s",
inet_ntoa(fdInfo.serverAddr.sin_addr), ntohs(fdInfo.serverAddr.sin_port), ret,
strerror(errno));
continue;
}
}
}
void HandleTcpReceived(FdInfo fdInfo) {
int addrlen = sizeof(struct sockaddr_in);
uint8_t buffer[BUFFER_SIZE] = {0};
while (threadRunF) {
int length = recvfrom(fdInfo.tunnelFd, buffer, sizeof(buffer), 0, (struct sockaddr *)&fdInfo.serverAddr,
(socklen_t *)&addrlen);
if (length < 0) {
if (errno != 11) {
NETMANAGER_VPN_LOGE("read tun device error: %{public}d, tunnelfd: %{public}d", errno, fdInfo.tunnelFd);
}
continue;
}
// Receive data from the UDP server and write the data to the vNIC.
NETMANAGER_VPN_LOGD("from [%{public}s:%{public}d] data: %{public}s, len: %{public}d",
inet_ntoa(fdInfo.serverAddr.sin_addr), ntohs(fdInfo.serverAddr.sin_port), buffer, length);
int ret = write(fdInfo.tunFd, buffer, length);
if (ret <= 0) {
NETMANAGER_VPN_LOGE("error Write To Tunfd, errno: %{public}d", errno);
}
}
}
static napi_value UdpConnect(napi_env env, napi_callback_info info) {
size_t argc = 2;
napi_value args[2] = {nullptr};
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
int32_t port = 0;
napi_get_value_int32(env, args[1], &port);
std::string ipAddr = GetStringFromValueUtf8(env, args[0]);
NETMANAGER_VPN_LOGI("ip: %{public}s port: %{public}d", ipAddr.c_str(), port);
// Establish a UDP tunnel.
int32_t sockFd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockFd == -1) {
NETMANAGER_VPN_LOGE("socket() error");
return 0;
}
struct timeval timeout = {1, 0};
setsockopt(sockFd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(struct timeval));
memset(&fdInfo.serverAddr, 0, sizeof(fdInfo.serverAddr));
fdInfo.serverAddr.sin_family = AF_INET;
fdInfo.serverAddr.sin_addr.s_addr = inet_addr(ipAddr.c_str()); // server's IP addr
fdInfo.serverAddr.sin_port = htons(port); // port
NETMANAGER_VPN_LOGI("Connection successful");
napi_value tunnelFd;
napi_create_int32(env, sockFd, &tunnelFd);
return tunnelFd;
}
static napi_value StartVpn(napi_env env, napi_callback_info info) {
size_t argc = 2;
napi_value args[2] = {nullptr};
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
napi_get_value_int32(env, args[0], &fdInfo.tunFd);
napi_get_value_int32(env, args[1], &fdInfo.tunnelFd);
if (threadRunF) {
threadRunF = false;
threadt1.join();
threadt2.join();
}
// Start two threads. One is used to read data from the vNIC, and the other is used to receive data from the server.
threadRunF = true;
std::thread tt1(HandleReadTunfd, fdInfo);
std::thread tt2(HandleTcpReceived, fdInfo);
threadt1 = std::move(tt1);
threadt2 = std::move(tt2);
NETMANAGER_VPN_LOGI("StartVpn successful");
napi_value retValue;
napi_create_int32(env, 0, &retValue);
return retValue;
}
static napi_value StopVpn(napi_env env, napi_callback_info info) {
size_t argc = 1;
napi_value args[1] = {nullptr};
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
int32_t tunnelFd;
napi_get_value_int32(env, args[0], &tunnelFd);
if (tunnelFd) {
close(tunnelFd);
tunnelFd = 0;
}
// Stop the two threads.
if (threadRunF) {
threadRunF = false;
threadt1.join();
threadt2.join();
}
NETMANAGER_VPN_LOGI("StopVpn successful");
napi_value retValue;
napi_create_int32(env, 0, &retValue);
return retValue;
}
EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports) {
napi_property_descriptor desc[] = {
{"udpConnect", nullptr, UdpConnect, nullptr, nullptr, nullptr, napi_default, nullptr},
{"startVpn", nullptr, StartVpn, nullptr, nullptr, nullptr, napi_default, nullptr},
{"stopVpn", nullptr, StopVpn, nullptr, nullptr, nullptr, napi_default, nullptr},
};
napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
return exports;
}
EXTERN_C_END
static napi_module demoModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "entry",
.nm_priv = ((void *)0),
.reserved = {0},
};
extern "C" __attribute__((constructor)) void RegisterEntryModule(void) {
napi_module_register(&demoModule);
}
```
......@@ -315,6 +315,7 @@
- [@ohos.net.statistics (Traffic Management)](js-apis-net-statistics.md)
- [@ohos.net.webSocket (WebSocket Connection)](js-apis-webSocket.md)
- [@ohos.request (Upload and Download)](js-apis-request.md)
- [@ohos.net.vpn (VPN Management)](js-apis-net-vpn.md)
- Connectivity
- [@ohos.bluetooth.a2dp (Bluetooth a2dp Module)(Recommended)](js-apis-bluetooth-a2dp.md)
......
......@@ -89,9 +89,11 @@ Specifies whether background applications are allowed to access the network. Thi
**Example**
```js
policy.setBackgroundAllowed(true).then(function (error) {
console.log(JSON.stringify(error))
})
policy.setBackgroundAllowed(true).then(() => {
console.log("setBackgroundAllowed success");
}).catch(error => {
console.log(JSON.stringify(error));
});
```
## policy.isBackgroundAllowed<sup>10+</sup>
......@@ -164,10 +166,11 @@ Checks whether the current application is allowed to access the network when run
**Example**
```js
policy.isBackgroundAllowed().then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
policy.isBackgroundAllowed().then((data) => {
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
});
```
## policy.setPolicyByUid<sup>10+</sup>
......@@ -248,9 +251,11 @@ Sets the metered network access policy for the application specified by a given
**Example**
```js
policy.setPolicyByUid(11111, policy.NetUidPolicy.NET_POLICY_NONE).then(function (error) {
console.log(JSON.stringify(error))
})
policy.setPolicyByUid(11111, policy.NetUidPolicy.NET_POLICY_NONE).then(() => {
console.log("setPolicyByUid success");
}).catch(error => {
console.log(JSON.stringify(error));
});
```
## policy.getPolicyByUid<sup>10+</sup>
......@@ -329,10 +334,11 @@ Obtains the network access policy for the application specified by a given UID.
**Example**
```js
policy.getPolicyByUid(11111).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
policy.getPolicyByUid(11111).then((data) => {
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
});
```
## policy.getUidsByPolicy<sup>10+</sup>
......@@ -412,10 +418,11 @@ Obtains all UIDs that match the specified network policy. This API uses a promis
**Example**
```js
policy.getUidsByPolicy(11111).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
policy.getUidsByPolicy(11111).then((data) => {
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
});
```
## policy.getNetQuotaPolicies<sup>10+</sup>
......@@ -487,11 +494,11 @@ Obtains the network quota policies. This API uses a promise to return the result
**Example**
```js
policy.getNetQuotaPolicies().then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
policy.getNetQuotaPolicies().then((data) => {
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
});
```
## policy.setNetQuotaPolicies<sup>10+</sup>
......@@ -608,9 +615,11 @@ let netquotapolicy = {
netQuotaPolicyList.push(netquotapolicy);
policy.setNetQuotaPolicies(netQuotaPolicyList).then(function (error) {
console.log(JSON.stringify(error))
})
policy.setNetQuotaPolicies(netQuotaPolicyList).then(() => {
console.log("setNetQuotaPolicies success");
}).catch(error => {
console.log(JSON.stringify(error));
});
```
## policy.isUidNetAllowed<sup>10+</sup>
......@@ -692,10 +701,11 @@ Checks whether the application specified by a given UID is allowed to access a m
**Example**
```js
policy.isUidNetAllowed(11111, true).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
policy.isUidNetAllowed(11111, true).then((data) => {
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
});
```
## policy.isUidNetAllowed<sup>10+</sup>
......@@ -777,10 +787,11 @@ Checks whether the application specified by a given UID is allowed to access the
**Example**
```js
policy.isUidNetAllowed(11111, 'wlan0').then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
policy.isUidNetAllowed(11111, 'wlan0').then((data) => {
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
});
```
## policy.setDeviceIdleTrustlist<sup>10+</sup>
......@@ -861,9 +872,11 @@ Adds applications specified by given UIDs to the device idle allowlist. This API
**Example**
```js
policy.setDeviceIdleTrustlist([11111,22222], true).then(function (error) {
console.log(JSON.stringify(error))
})
policy.setDeviceIdleTrustlist([11111,22222], true).then(() => {
console.log("setDeviceIdleTrustlist success");
}).catch(error => {
console.log(JSON.stringify(error));
});
```
## policy.getDeviceIdleTrustlist<sup>10+</sup>
......@@ -934,10 +947,11 @@ Obtains the UIDs of applications that are on the device idle allowlist. This API
**Example**
```js
policy.getDeviceIdleTrustlist().then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
policy.getDeviceIdleTrustlist().then((data) => {
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
});
```
## policy.getBackgroundPolicyByUid<sup>10+</sup>
......@@ -1017,10 +1031,11 @@ Obtains the background network policy for the application specified by a given U
**Example**
```js
policy.getBackgroundPolicyByUid(11111).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
policy.getBackgroundPolicyByUid(11111).then((data) => {
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
});
```
## policy.resetPolicies<sup>10+</sup>
......@@ -1099,9 +1114,11 @@ Restores all the policies (cellular network, background network, firewall, and a
**Example**
```js
policy.resetPolicies('1').then(function (error) {
console.log(JSON.stringify(error))
})
policy.resetPolicies('1').then(() => {
console.log("resetPolicies success");
}).catch(error => {
console.log(JSON.stringify(error));
});
```
## policy.updateRemindPolicy<sup>10+</sup>
......@@ -1186,9 +1203,11 @@ Updates a reminder policy. This API uses a promise to return the result.
```js
import connection from '@ohos.net.connection';
policy.updateRemindPolicy(connection.NetBearType.BEARER_CELLULAR, '1', policy.RemindType.REMIND_TYPE_WARNING).then(function (error) {
console.log(JSON.stringify(error))
})
policy.updateRemindPolicy(connection.NetBearType.BEARER_CELLULAR, '1', policy.RemindType.REMIND_TYPE_WARNING).then(() => {
console.log("updateRemindPolicy success");
}).catch(error => {
console.log(JSON.stringify(error));
});
```
## policy.setPowerSaveTrustlist<sup>10+</sup>
......@@ -1269,9 +1288,11 @@ Sets whether to add the application specified by a given UID to the power-saving
**Example**
```js
policy.setPowerSaveTrustlist([11111,22222], true).then(function (error) {
console.log(JSON.stringify(error))
})
policy.setPowerSaveTrustlist([11111,22222], true).then(() => {
console.log("setPowerSaveTrustlist success");
}).catch(error => {
console.log(JSON.stringify(error));
});
```
## policy.getPowerSaveTrustlist<sup>10+</sup>
......@@ -1343,10 +1364,11 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi
**Example**
```js
policy.getPowerSaveTrustlist().then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
policy.getPowerSaveTrustlist().then((data) => {
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
});
```
## policy.on
......
# @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
```js
import vpn from '@ohos.net.vpn';
```
## vpn.createVpnConnection
createVpnConnection(context: AbilityContext): VpnConnection
Creates a VPN connection.
**System capability**: SystemCapability.Communication.NetManager.Vpn
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| context | [AbilityContext](js-apis-inner-application-uiAbilityContext.md#uiabilitycontext) | Yes | Specified context. |
**Return value**
| Type | Description |
| :--------------------------------- | :---------------------- |
| [VpnConnection](#vpnconnection) | VPN connection object.|
**Error codes**
For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
| ID| Error Message |
| ------- | ----------------------------- |
| 401 | Parameter error. |
**Example**
Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
globalThis.context = this.context;
}
}
let context = globalThis.context;
VpnConnection = vpn.createVpnConnection(context);
console.info("vpn onInit: " + JSON.stringify(VpnConnection));
```
## VpnConnection
Defines a VPN connection object. Before calling **VpnConnection** APIs, you need to create a VPN connection object by calling [vpn.createVpnConnection](#vpncreatevpnconnection).
### 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**
| Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| config | [VpnConfig](#vpnconfig) | Yes | VPN configuration. |
| 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.|
**Error codes**
For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2203001 | VPN creation denied, please check the user type. |
| 2203002 | VPN exist already, please execute destroy first. |
**Example**
```js
let config = {
addresses: [{
address: {
address: "10.0.0.5",
family: 1
},
prefixLength: 24,
}],
routes: [],
mtu: 1400,
dnsAddresses:[
"114.114.114.114"
],
trustedApplications:[],
blockedApplications:[]
}
VpnConnection.setUp(config, (error, data) => {
console.info(JSON.stringify(error));
console.info("tunfd: " + JSON.stringify(data));
})
```
### 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**
| Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| config | [VpnConfig](#vpnconfig) | Yes | VPN configuration. |
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<number\> | The obtaining result is returned in Promise format. The file descriptor fd of the specified virtual network adapter is returned.|
**Error codes**
For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2203001 | VPN creation denied, please check the user type. |
| 2203002 | VPN exist already, please execute destroy first. |
**Example**
```js
let config = {
addresses: [{
address: {
address: "10.0.0.5",
family: 1
},
prefixLength: 24,
}],
routes: [],
mtu: 1400,
dnsAddresses:[
"114.114.114.114"
],
trustedApplications:[],
blockedApplications:[]
}
VpnConnection.setUp(config).then((data) => {
console.info(TAG + "setUp success, tunfd: " + JSON.stringify(data))
}).catch(err => {
console.info(TAG + "setUp fail" + JSON.stringify(err))
})
```
### 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**
| Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| socketFd | number | Yes | Socket file descriptor. It can be obtained through [getSocketFd](js-apis-socket.md#getsocketfd10). |
| 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.|
**Error codes**
For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2203004 | Invalid socket file descriptor. |
**Example**
```js
import socket from "@ohos.net.socket";
var tcp = socket.constructTCPSocketInstance();
tcp.bind({
address: "0.0.0.0",
family: 1
})
let connectAddress = {
address: "192.168.1.11",
port: 8888,
family: 1
};
tcp.connect({
address: connectAddress, timeout: 6000
})
tcp.getSocketFd().then((tunnelfd) => {
console.info("tunenlfd: " + tunnelfd);
VpnConnection.protect(tunnelfd, (error) => {
console.info(JSON.stringify(error));
})
})
```
### 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 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**
| Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| socketFd | number | Yes | Socket file descriptor. It can be obtained through [getSocketFd](js-apis-socket.md#getsocketfd10-1). |
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| 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](../errorcodes/errorcode-net-vpn.md).
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2200001 | Invalid parameter value. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
| 2203004 | Invalid socket file descriptor. |
**Example**
```js
import socket from "@ohos.net.socket";
var tcp = socket.constructTCPSocketInstance();
tcp.bind({
address: "0.0.0.0",
family: 1
})
let connectAddress = {
address: "192.168.1.11",
port: 8888,
family: 1
};
tcp.connect({
address: connectAddress, timeout: 6000
})
tcp.getSocketFd().then((tunnelfd) => {
console.info("tunenlfd: " + tunnelfd);
VpnConnection.protect(tunnelfd).then(() => {
console.info("protect success.")
}).catch(err => {
console.info("protect fail" + JSON.stringify(err))
})
})
```
### 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**
| Name | Type | Mandatory| Description |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| 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.|
**Error codes**
For details about the error codes, see [VPN Error Codes](../errorcodes/errorcode-net-vpn.md).
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Example**
```js
VpnConnection.destroy((error) => {
console.info(JSON.stringify(error));
})
```
### 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**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| 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](../errorcodes/errorcode-net-vpn.md).
| ID| Error Message |
| ------- | ----------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 2200002 | Operation failed. Cannot connect to service. |
| 2200003 | System internal error. |
**Example**
```js
VpnConnection.destroy().then(() => {
console.info("destroy success.")
}).catch(err => {
console.info("destroy fail" + JSON.stringify(err))
});
```
## VpnConfig
Defines the VPN configuration.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Vpn
| Name| Type| Mandatory| Description|
| ------- | ------ | -- |------------------------------ |
| addresses | Array\<[LinkAddress](js-apis-net-connection.md#linkaddress8)\> | Yes| IP address of the vNIC.|
| routes | Array\<[RouteInfo](js-apis-net-connection.md#routeinfo8)\> | No| Route information of the vNIC.|
| dnsAddresses | Array\<string\> | No| IP address of the DNS server.|
| searchDomains | Array\<string\> | No| List of DNS search domains.|
| mtu | number | No| Maximum transmission unit (MTU), in bytes.|
| isIPv4Accepted | boolean | No| Whether IPv4 is supported. The default value is **true**.|
| isIPv6Accepted | boolean | No| Whether IPv6 is supported. The default value is **false**.|
| isLegacy | boolean | No| Whether the built-in VPN is supported. The default value is **false**.|
| isBlocking | boolean | No| Whether the blocking mode is used. The default value is **false**.|
| trustedApplications | Array\<string\> | No| List of trusted applications, which are represented by bundle names of the string type.|
| blockedApplications | Array\<string\> | No| List of blocked applications, which are represented by bundle names of the string type.|
......@@ -6,7 +6,7 @@
## 3301000 Location Service Unavailable
**Error Message**
**Error Information**
Location service is unavailable.
......@@ -28,7 +28,7 @@ Stop calling the API.
## 3301100 Location Service Unavailable Because of Switch Toggled Off
**Error Message**
**Error Information**
The location switch is off.
......@@ -44,15 +44,15 @@ The location service switch is toggled off, which makes basic functions such as
Display a prompt asking for enabling the location service.
## 3301200 Failure to Obtain the Positioning Result
## 3301200 Failed to Obtain the Positioning Result
**Error Message**
**Error Information**
Failed to obtain the geographical location.
**Description**
This error code is reported when the location service fails, and no positioning result is obtained.
This error code is reported if the location service has failed, leading to a failure to obtain the positioning result.
**Possible Causes**
......@@ -64,15 +64,15 @@ This error code is reported when the location service fails, and no positioning
Initiate a positioning request again.
## 3301300 Reverse Geocoding Query Failure
## 3301300 Query Failed During Reverse Geocoding
**Error Message**
**Error Information**
Reverse geocoding query failed.
**Description**
This error code is reported for a reverse geocoding query failure.
This error code is reported if the query during reverse geocoding has failed.
**Possible Causes**
......@@ -80,17 +80,17 @@ Network connection is poor, which makes the request fail to be sent from the dev
**Solution**
Try the reverse geocoding query again.
Perform a query again.
## 3301400 Geocoding Query Failure
## 3301400 Query Failed During Geocoding
**Error Message**
**Error Information**
Geocoding query failed.
**Description**
This error code is reported for a geocoding query failure.
This error code is reported if the query during geocoding has failed.
**Possible Causes**
......@@ -98,17 +98,17 @@ Network connection is poor, which makes the request fail to be sent from the dev
**Solution**
Try the geocoding query again.
Perform a query again.
## 3301500 Area Information Query Failure
## 3301500 Area Information Query Failed
**Error Message**
**Error Information**
Failed to query the area information.
**Description**
This error code is reported for the failure to query the area information (including the country code).
This error code is reported if the query of the area information (including the country code) has failed.
**Possible Causes**
......@@ -118,15 +118,15 @@ The correct area information is not found.
Stop calling the API for querying the country code.
## 3301600 Geofence Operation Failure
## 3301600 Geofence Operation Failed
**Error Message**
**Error Information**
Failed to operate the geofence.
**Description**
This error code is reported when an operation (like adding, deleting, pausing, and resuming) fails to be performed on the geofence.
This error code is reported if a geofence operation, for example, adding, deleting, pausing, or resuming a geofence, has failed.
**Possible Causes**
......@@ -140,13 +140,13 @@ Stop calling the geofence operation API.
## 3301700 No Response to the Request
**Error Message**
**Error Information**
No response to the request.
**Description**
This error code is reported when no response is received for an asynchronous request that requires a user to click a button for confirmation or requires a response from the GNSS chip or network server.
This error code is reported if no response is received for an asynchronous request that requires a user to click a button for confirmation or requires a response from the GNSS chip or network server.
**Possible Causes**
......@@ -159,3 +159,25 @@ This error code is reported when no response is received for an asynchronous req
**Solution**
Stop calling relevant APIs.
## 3301800 Failed to Start Wi-Fi or Bluetooth Scanning
**Error Information**
Failed to start WiFi or Bluetooth scanning.
**Description**
This error code is reported if Wi-Fi or Bluetooth scanning fails to start.
**Possible Causes**
1. The Wi-Fi or Bluetooth service incurs an internal error.
2. Power consumption control is activated because of low battery level.
3. Wi-Fi or Bluetooth is not enabled.
**Solution**
Turn off Wi-Fi or Bluetooth, and then turn it on again.
# VPN Error Codes
> **NOTE**
>
> This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](errorcode-universal.md).
## 2203001 Failed to Create a VPN
**Error Information**
VPN creation denied, please check the user type.
**Description**
This error code is reported if a VPN fails to be created.
**Possible Causes**
The login user does not have the operation permission. Specifically, the GUEST user does not have the permission to call the **setUp** API.
**Solution**
Check the type of the login user.
## 2203002 VPN Already Exists
**Error Information**
VPN exist already, please execute destroy first.
**Description**
This error code is reported if a VPN already exists.
**Possible Causes**
The VPN has been created.
**Solution**
Call the **destroy** API to destroy the existing VPN, and then call the **setUp** API.
## 2203004 Invalid Descriptor
**Error Information**
Invalid socket file descriptor.
**Description**
This error code is reported if the socket file descriptor is invalid.
**Possible Causes**
A TCP socket connection fails to be established.
**Solution**
Check whether a TCP socket connection is set up successfully.
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册