@ohos.net.connection (Network Connection Management)
The network connection management module provides basic network management capabilities. You can obtain the default active network, the list of all active networks, and network capability information.
NOTE
The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Unless otherwise specified, the APIs of this module do not support concurrent calls.
Modules to Import
import { connection } from '@kit.NetworkKit';
connection.createNetConnection
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection
Creates a NetConnection object, which can be used to listen for the network status. netSpecifier specifies the network to be listened for, and timeout indicates the timeout duration (ms). netSpecifier is a mandatory parameter for timeout. If neither of them is present, the default network is used.
NOTE
To listen for the network status, after creating a NetConnection object, you need to call register to register the notification of the specified network status change.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| netSpecifier | NetSpecifier | No | Specification of the network to be listened for. If this parameter is not specified, the default network is listened for. |
| timeout | number | No | Timeout interval for obtaining the network specified by netSpecifier. The input value must be an uint32_t integer. This parameter is valid only when netSpecifier is present. The default value is 0. Note: If the network to be listened for does not exist, the system attempts to activate the network. If the timeout interval is exceeded and the network status listener is registered, the netUnavailable event is triggered. |
Return value
| Type | Description |
|---|---|
| NetConnection | Type of the network connection object to be listened for. |
Example
import { connection } from '@kit.NetworkKit';
// Example 1: Only the default network is concerned. You do not need to specify the netSpecifier parameter. If the timeout parameter is not passed, the timeout interval is not used. In this case, the value of timeout is 0.
let netConnection = connection.createNetConnection();
// Example 2: Only the cellular network is concerned. You need to specify the network type to cellular.
let timeout = 1000;
let netConnectionCellular = connection.createNetConnection({
netCapabilities: {
bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
}
}, timeout);
// Example 3: Both the cellular and Wi-Fi networks are concerned. You need to specify the network type to cellular and Wi-Fi.
let netConnectionCellularAndWifi = connection.createNetConnection({
netCapabilities: {
bearerTypes: [connection.NetBearType.BEARER_CELLULAR,
connection.NetBearType.BEARER_WIFI]
}
});
connection.getDefaultNet
getDefaultNet(callback: AsyncCallback<NetHandle>): void
Obtains the network handle used by the system by default, including the network ID. This API uses an asynchronous callback to return the result.
NOTE
Default network used by the system. The network must have the NET_CAPABILITY_INTERNET capability and is not a VPN network.
The return value of this interface is determined by the system and is irrelevant to whether the application specifies a network.
Generally, the priority is as follows: Ethernet (PC) | Bluetooth (watch) > Wi-Fi > Cellular. In special cases, the actual return result prevails.
NetHandle is the unique identifier of the network. If no network is available, 0 is returned. It can be used by getNetCapabilities to query more network information.
Required permission: ohos.permission.GET_NETWORK_INFO
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<NetHandle> | Yes | Callback used to return the result. When the network handle of the default activated network is successfully obtained, error is undefined and data is the network handle of the default network; otherwise, error is an error object. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getDefaultNet((error: BusinessError, data: connection.NetHandle) => {
if (error) {
console.error(`Failed to get default net. Code:${error.code}, message:${error.message}`);
return;
}
console.info("Succeeded to get data: " + JSON.stringify(data));
});
connection.getDefaultNet
getDefaultNet(): Promise<NetHandle>
Obtains the network handle used by the system by default, including the network ID. This API uses a promise to return the result.
NOTE
Default network used by the system. The network must have the NET_CAPABILITY_INTERNET capability and is not a VPN network.
The return value of this interface is determined by the system and is irrelevant to whether the application specifies a network.
Generally, the priority is as follows: Ethernet (PC) | Bluetooth (watch) > Wi-Fi > Cellular. In special cases, the actual returned result prevails.
NetHandle is the unique identifier of the network. If no network is available, 0 is returned. It can be used by getNetCapabilities to query more network information.
Required permission: ohos.permission.GET_NETWORK_INFO
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Communication.NetManager.Core
Return value
| Type | Description |
|---|---|
| Promise<NetHandle> | Promise used to return the network handle of the default network. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
connection.getDefaultNet().then((data: connection.NetHandle) => {
console.info("Succeeded to get data: " + JSON.stringify(data));
});
connection.getDefaultNetSync9+
getDefaultNetSync(): NetHandle
Obtains the network handle used by the system by default, including the network ID. This API returns the result synchronously.
NOTE
Default network used by the system. The network must have the NET_CAPABILITY_INTERNET capability and is not a VPN network.
The return value of this interface is determined by the system and is irrelevant to whether the application specifies a network.
Generally, the priority is as follows: Ethernet (PC) | Bluetooth (watch) > Wi-Fi > Cellular. In special cases, the actual returned result prevails.
NetHandle is the unique identifier of the network. If no network is available, 0 is returned. It can be used by getNetCapabilities to query more network information.
Required permission: ohos.permission.GET_NETWORK_INFO
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Communication.NetManager.Core
Return value
| Type | Description |
|---|---|
| NetHandle | Network handle of the default network. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
let netHandle = connection.getDefaultNetSync();
connection.setAppHttpProxy11+
setAppHttpProxy(httpProxy: HttpProxy): void
Sets the application-level HTTP proxy configuration.
NOTE
If you want to use the proxy information configured by this API, set usingProxy in HttpRequestOptions to true to enable proxy forwarding. This API is used only for configuring proxy rules. It does not verify the validity of the proxy service.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| httpProxy | HttpProxy | Yes | Application-level HTTP proxy configuration. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
| 2100001 | Invalid http proxy. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { http } from '@kit.NetworkKit';
let exclusionStr = "192.168,baidu.com";
let exclusionArray = exclusionStr.split(',');
connection.setAppHttpProxy({
host: "192.168.xx.xxx",
port: 8080,
exclusionList: exclusionArray
} as connection.HttpProxy);
let httpRequest = http.createHttp();
let options: http.HttpRequestOptions = {
usingProxy: true, // This field specifies whether to use the network proxy. It is supported since API version 10.
};
// Initiate an HTTP request.
httpRequest.request("EXAMPLE_URL", options, (err: Error, data: http.HttpResponse) => {
if (!err) {
console.info(`Result: ${data.result}`);
console.info(`code: ${data.responseCode}`);
console.info(`type: ${JSON.stringify(data.resultType)}`);
console.info(`header: ${JSON.stringify(data.header)}`);
console.info(`cookies: ${data.cookies}`); // Cookies are supported since API version 8.
} else {
console.error(`error: ${JSON.stringify(err)}`);
}
});
connection.getDefaultHttpProxy10+
getDefaultHttpProxy(callback: AsyncCallback<HttpProxy>): void
Obtains the default HTTP proxy configuration of the network. This API uses an asynchronous callback to return the result.
NOTE
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<HttpProxy> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, error is undefined and data is the global HTTP proxy configuration. Otherwise, error is an error object. |
Error codes
For details about the error codes, see Network Connection Management Error Codes.
| ID | Error Message |
|---|---|
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getDefaultHttpProxy((error: BusinessError, data: connection.HttpProxy) => {
if (error) {
console.error(`Failed to get default http proxy. Code:${error.code}, message:${error.message}`);
return;
}
console.info("Succeeded to get data" + JSON.stringify(data));
});
connection.getDefaultHttpProxy10+
getDefaultHttpProxy(): Promise<HttpProxy>
Obtains the default HTTP proxy configuration of the network. This API uses a promise to return the result.
NOTE
System capability: SystemCapability.Communication.NetManager.Core
Return value
| Type | Description |
|---|---|
| Promise<HttpProxy> | Promise used to return the result. |
Error codes
For details about the error codes, see Network Connection Management Error Codes.
| ID | Error Message |
|---|---|
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getDefaultHttpProxy().then((data: connection.HttpProxy) => {
console.info(JSON.stringify(data));
}).catch((error: BusinessError) => {
console.info(JSON.stringify(error));
});
connection.getAppNet9+
getAppNet(callback: AsyncCallback<NetHandle>): void
Obtains the network handle bound to an application. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<NetHandle> | Yes | Callback used to return the result. If information about the network bound to the application is successfully obtained, error is undefined and data is the obtained network information. Otherwise, error is an error object. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getAppNet((error: BusinessError, data: connection.NetHandle) => {
if (error) {
console.error(`Failed to get App net. Code:${error.code}, message:${error.message}`);
return;
}
console.info("Succeeded to get data: " + JSON.stringify(data));
})
connection.getAppNet9+
getAppNet(): Promise<NetHandle>
Obtains the network information bound to an application. This API uses a promise to return the result.
System capability: SystemCapability.Communication.NetManager.Core
Return value
| Type | Description |
|---|---|
| Promise<NetHandle> | Promise used to return the result. |
Error codes
For details about the error codes, see Network Connection Management Error Codes.
| ID | Error Message |
|---|---|
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getAppNet().then((data: connection.NetHandle) => {
console.info(JSON.stringify(data));
}).catch((error: BusinessError) => {
console.info(JSON.stringify(error));
});
connection.getAppNetSync10+
getAppNetSync(): NetHandle
Obtains the network information bound to an application. This API returns the result synchronously.
System capability: SystemCapability.Communication.NetManager.Core
Return value
| Type | Description |
|---|---|
| NetHandle | Data network bound to the application. |
Error codes
For details about the error codes, see Network Connection Management Error Codes.
| ID | Error Message |
|---|---|
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
let netHandle = connection.getAppNetSync();
connection.setAppNet9+
setAppNet(netHandle: NetHandle, callback: AsyncCallback<void>): void
Binds an application to the network specified by netHandle, so that the application can access the external network only through this network. This API uses an asynchronous callback to return the result.
Required permissions: ohos.permission.INTERNET
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| netHandle | NetHandle | Yes | Network handle. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the application is successfully bound to the specified network, error is undefined. Otherwise, error is an error object. |
NOTE
When the application no longer uses the network or the network is unavailable, you need to unbind the application from the specified network to prevent the application from failing to access the Internet.
To unbind the application from the specified network, call setAppNet and pass a NetHandle object with netId set to 0. For details, see the following example.
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
netHandle.netId = 0;
connection.setAppNet(netHandle, (error: BusinessError, data: void) => {
if (error) {
console.error(`Failed to get default net. Code:${error.code}, message:${error.message}`);
return;
}
console.info("Succeeded to get data: " + JSON.stringify(data));
});
});
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
If an application is bound to a Wi-Fi network and the Wi-Fi signal is weak or the network is disconnected, the application cannot access the Internet if it is not unbound.
The following example binds the application to a Wi-Fi network. It uses the on("netAvailable") API to bind the application when the Wi-Fi network is available, and the on("netLost") API to unbind the application and switch to the default network when the Wi-Fi network is unavailable.
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
// Create a NetConnection object. To bind only to the Wi-Fi network, set the network type to Wi-Fi.
let netCon = connection.createNetConnection({
netCapabilities: {
bearerTypes: [connection.NetBearType.BEARER_WIFI]
}
});
// Use the on API to enable listening for netAvailable events.
netCon.on('netAvailable', (netHandle: connection.NetHandle) => {
console.info("Succeeded to get data: " + JSON.stringify(netHandle));
connection.setAppNet(netHandle, (error: BusinessError, data: void) => {
if (error) {
console.error(`Failed to setAppNet. Code:${error.code}, message:${error.message}`);
return;
}
console.info("Succeeded to setAppNet, netid: " + JSON.stringify(netHandle.netId));
});
});
// Use the on API to enable listening for netLost events.
netCon.on('netLost', (netHandle: connection.NetHandle) => {
console.info("Succeeded to get data: " + JSON.stringify(netHandle));
// When the network is lost, proactively unbind the specified network.
netHandle.netId = 0;
connection.setAppNet(netHandle, (error: BusinessError, data: void) => {
if (error) {
console.error(`Failed to setAppNet. Code:${error.code}, message:${error.message}`);
return;
}
console.info("Succeeded to setAppNet, netid: " + JSON.stringify(netHandle.netId));
});
});
// Register a listener for network status change events. This API must be called after the on API.
netCon.register((error: BusinessError) => {
if (error) {
console.error(JSON.stringify(error));
}
});
connection.setAppNet9+
setAppNet(netHandle: NetHandle): Promise<void>
Binds an application to the network specified by netHandle, so that the application can access the external network only through this network. This API uses a promise to return the result. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| netHandle | NetHandle | Yes | Network handle. |
NOTE
When the application no longer uses the network or the network is unavailable, you need to unbind the application from the specified network to prevent the application from failing to access the Internet.
To unbind the application from the specified network, call setAppNet and pass a NetHandle object with netId set to 0. For details, see the following example.
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
netHandle.netId = 0;
connection.setAppNet(netHandle).then(() => {
console.info("setAppNet success");
}).catch((error: BusinessError) => {
console.error(`Failed to setAppNet. Code:${error.code}, message:${error.message}`);
})
});
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
If an application is bound to a Wi-Fi network and the Wi-Fi signal is weak or the network is disconnected, the application cannot access the Internet if it is not unbound.
The following example binds the application to a Wi-Fi network. It uses the on("netAvailable") API to bind the application when the Wi-Fi network is available, and the on("netLost") API to unbind the application and switch to the default network when the Wi-Fi network is unavailable.
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
// Create a NetConnection object. To bind only to the Wi-Fi network, set the network type to Wi-Fi.
let netCon = connection.createNetConnection({
netCapabilities: {
bearerTypes: [connection.NetBearType.BEARER_WIFI]
}
});
// Use the on API to enable listening for netAvailable events.
netCon.on('netAvailable', (netHandle: connection.NetHandle) => {
console.info("Succeeded to get data: " + JSON.stringify(netHandle));
connection.setAppNet(netHandle).then(() => {
console.info("setAppNet success, netid: " + JSON.stringify(netHandle.netId));
}).catch((error: BusinessError) => {
console.error(`Failed to setAppNet. Code:${error.code}, message:${error.message}`);
})
});
// Use the on API to enable listening for netLost events.
netCon.on('netLost', (netHandle: connection.NetHandle) => {
console.info("Succeeded to get data: " + JSON.stringify(netHandle));
// When the network is lost, proactively unbind the specified network.
netHandle.netId = 0;
connection.setAppNet(netHandle).then(() => {
console.info("setAppNet success, netid: " + JSON.stringify(netHandle.netId));
}).catch((error: BusinessError) => {
console.error(`Failed to setAppNet. Code:${error.code}, message:${error.message}`);
})
});
// Register a listener for network status change events. This API must be called after the on API.
netCon.register((error: BusinessError) => {
if (error) {
console.error(JSON.stringify(error));
}
});
connection.getAllNets
getAllNets(callback: AsyncCallback<Array<NetHandle>>): void
Obtains the list of all connected networks. This API uses an asynchronous callback to return the result.
Required permission: ohos.permission.GET_NETWORK_INFO
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<Array<NetHandle>> | Yes | Callback used to return the result. If the list of all connected networks is obtained successfully, error is undefined and data is the list of activated networks. Otherwise, error is an error object. Note: If Wi-Fi and cellular data are both enabled, and no application specifies the use of cellular data, only Wi-Fi is activated. In this case, only the NetHandle of Wi-Fi is returned. The NetHandle of Wi-Fi and cellular data can be obtained at the same time only when a specific application enables the cellular network. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getAllNets((error: BusinessError, data: connection.NetHandle[]) => {
if (error) {
console.error(`Failed to get all nets. Code:${error.code}, message:${error.message}`);
return;
}
console.info("Succeeded to get data: " + JSON.stringify(data));
});
connection.getAllNets
getAllNets(): Promise<Array<NetHandle>>
Obtains the list of all connected networks. This API uses a promise to return the result.
Required permission: ohos.permission.GET_NETWORK_INFO
System capability: SystemCapability.Communication.NetManager.Core
Return value
| Type | Description |
|---|---|
| Promise<Array<NetHandle>> | Promise used to return the list of activated networks. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
connection.getAllNets().then((data: connection.NetHandle[]) => {
console.info("Succeeded to get data: " + JSON.stringify(data));
});
connection.getAllNetsSync10+
getAllNetsSync(): Array<NetHandle>
Obtains the list of all connected networks. This API returns the result synchronously.
Required permission: ohos.permission.GET_NETWORK_INFO
System capability: SystemCapability.Communication.NetManager.Core
Return value
| Type | Description |
|---|---|
| Array<NetHandle> | List of all connected networks. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
let netHandle = connection.getAllNetsSync();
connection.getConnectionProperties
getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback<ConnectionProperties>): void
Obtains the connection information of the data network specified by NetHandle, including the NIC name, domain name, link information, route information, network address, and maximum transmission unit. This API uses an asynchronous callback to return the result.
Required permission: ohos.permission.GET_NETWORK_INFO
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| netHandle | NetHandle | Yes | Network handle. |
| callback | AsyncCallback<ConnectionProperties> | Yes | Callback used to return the result. If the connection properties of the network specified by netHandle is obtained successfully, error is undefined and data is the obtained network connection information. Otherwise, error is an error object. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
// Example: Obtain the connection information of the default network.
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
if (netHandle.netId == 0) {
// If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements.
return;
}
connection.getConnectionProperties(netHandle, (error: BusinessError, data: connection.ConnectionProperties) => {
if (error) {
console.error(`Failed to get connection properties. Code:${error.code}, message:${error.message}`);
return;
}
console.info("Succeeded to get data: " + JSON.stringify(data));
})
});
connection.getConnectionProperties
getConnectionProperties(netHandle: NetHandle): Promise<ConnectionProperties>
Obtains the connection information of the data network specified by NetHandle, including the NIC name, domain name, link information, route information, network address, and maximum transmission unit. This API uses a promise to return the result.
Required permission: ohos.permission.GET_NETWORK_INFO
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| netHandle | NetHandle | Yes | Handle of the data network. |
Return value
| Type | Description |
|---|---|
| Promise<ConnectionProperties> | Promise used to return the network connection information. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
if (netHandle.netId == 0) {
// If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements.
return;
}
connection.getConnectionProperties(netHandle).then((data: connection.ConnectionProperties) => {
console.info("Succeeded to get data: " + JSON.stringify(data));
})
});
connection.getConnectionPropertiesSync10+
getConnectionPropertiesSync(netHandle: NetHandle): ConnectionProperties
Obtains the connection information of the data network specified by NetHandle, including the NIC name, domain name, link information, route information, network address, and maximum transmission unit. This API returns the result synchronously.
Required permission: ohos.permission.GET_NETWORK_INFO
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| netHandle | NetHandle | Yes | Network handle. |
Return value
| Type | Description |
|---|---|
| ConnectionProperties | Network connection information. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let netHandle: connection.NetHandle;
let connectionproperties: connection.ConnectionProperties;
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
if (netHandle.netId == 0) {
// If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements.
return;
}
netHandle = connection.getDefaultNetSync();
connectionproperties = connection.getConnectionPropertiesSync(netHandle);
console.info("Succeeded to get connectionproperties: " + JSON.stringify(connectionproperties));
});
connection.getNetCapabilities
getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback<NetCapabilities>): void
Obtains the network capability set of the data network specified by NetHandle, including the uplink and downlink bandwidth, specific network capabilities, and network type. This API uses an asynchronous callback to return the result.
Required permission: ohos.permission.GET_NETWORK_INFO
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| netHandle | NetHandle | Yes | Network handle. |
| callback | AsyncCallback<NetCapabilities> | Yes | Callback used to return the result. If the capability set of the network specified by NetHandle is successfully obtained, error is undefined, and data is the obtained network capability set. Otherwise, error is an error object. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
if (netHandle.netId == 0) {
// If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements.
return;
}
connection.getNetCapabilities(netHandle, (error: BusinessError, data: connection.NetCapabilities) => {
if (error) {
console.error(`Failed to get net capabilities. Code:${error.code}, message:${error.message}`);
return;
}
console.info("Succeeded to get data: " + JSON.stringify(data));
})
}).catch((error: BusinessError) => {
console.error(JSON.stringify(error));
});
connection.getNetCapabilities
getNetCapabilities(netHandle: NetHandle): Promise<NetCapabilities>
Obtains the network capability set of the data network specified by NetHandle, including the uplink and downlink bandwidth, specific network capabilities, and network type. This API uses a promise to return the result.
Required permission: ohos.permission.GET_NETWORK_INFO
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| netHandle | NetHandle | Yes | Network handle. |
Return value
| Type | Description |
|---|---|
| Promise<NetCapabilities> | Promise used to return the network capability set. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
if (netHandle.netId == 0) {
// If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements.
return;
}
connection.getNetCapabilities(netHandle).then((data: connection.NetCapabilities) => {
console.info("Succeeded to get data: " + JSON.stringify(data));
})
}).catch((error: BusinessError) => {
console.error(JSON.stringify(error));
});
connection.getNetCapabilitiesSync10+
getNetCapabilitiesSync(netHandle: NetHandle): NetCapabilities
Obtains the network capability information of the data network specified by NetHandle, including the uplink and downlink bandwidth, specific network capabilities, and network type. This API returns the result synchronously.
Required permission: ohos.permission.GET_NETWORK_INFO
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| netHandle | NetHandle | Yes | Network handle. |
Return value
| Type | Description |
|---|---|
| NetCapabilities | Network capability set. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let netHandle: connection.NetHandle;
let getNetCapabilitiesSync: connection.NetCapabilities;
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
if (netHandle.netId == 0) {
// If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements.
return;
}
getNetCapabilitiesSync = connection.getNetCapabilitiesSync(netHandle);
console.info("Succeeded to get net capabilities sync: " + JSON.stringify(getNetCapabilitiesSync));
});
connection.isDefaultNetMetered9+
isDefaultNetMetered(callback: AsyncCallback<boolean>): void
Checks whether the data traffic over the current default network is metered. For example, data traffic over Wi-Fi is not metered, whereas that over cellular networks is. This API uses an asynchronous callback to return the result.
Required permission: ohos.permission.GET_NETWORK_INFO
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value true indicates that the data traffic over the current network is metered, and the value false indicates the opposite. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.isDefaultNetMetered((error: BusinessError, data: boolean) => {
console.error(JSON.stringify(error));
console.info('data: ' + data);
});
connection.isDefaultNetMetered9+
isDefaultNetMetered(): Promise<boolean>
Checks whether the data traffic over the current default network is metered. For example, data traffic over Wi-Fi is not metered, whereas that over cellular networks is. This API uses a promise to return the result.
Required permission: ohos.permission.GET_NETWORK_INFO
System capability: SystemCapability.Communication.NetManager.Core
Return value
| Type | Description |
|---|---|
| Promise<boolean> | Promise used to return the result. The value true indicates that the data traffic over the current network is metered, and the value false indicates the opposite. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
connection.isDefaultNetMetered().then((data: boolean) => {
console.info('data: ' + data);
});
connection.isDefaultNetMeteredSync10+
isDefaultNetMeteredSync(): boolean
Checks whether the data traffic over the current network is metered. For example, data traffic over Wi-Fi is not metered, whereas that over cellular networks is. This API returns the result synchronously.
Required permission: ohos.permission.GET_NETWORK_INFO
System capability: SystemCapability.Communication.NetManager.Core
Return value
| Type | Description |
|---|---|
| boolean | Boolean value indicating whether data traffic over the current network is metered. The value true indicates that the data traffic is metered, and the value false indicates the opposite. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
let isMetered = connection.isDefaultNetMeteredSync();
connection.hasDefaultNet
hasDefaultNet(callback: AsyncCallback<boolean>): void
Checks whether there is an available network. This API uses an asynchronous callback to return the result. If there is an available network, getDefaultNet can be used to obtain the default network handle.
Required permission: ohos.permission.GET_NETWORK_INFO
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<boolean> | Yes | Callback used to return whether there is an available network. The value true indicates that a network is available, and the value false indicates the opposite. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.hasDefaultNet((error: BusinessError, data: boolean) => {
console.error(JSON.stringify(error));
console.info('data: ' + data);
});
connection.hasDefaultNet
hasDefaultNet(): Promise<boolean>
Checks whether there is an available network. This API uses a promise to return the result. If there is an available network, getDefaultNet can be used to obtain the default network handle.
Required permission: ohos.permission.GET_NETWORK_INFO
System capability: SystemCapability.Communication.NetManager.Core
Return value
| Type | Description |
|---|---|
| Promise<boolean> | Promise used to return whether there is an available network. The value true indicates that a network is available, and the value false indicates the opposite. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
connection.hasDefaultNet().then((data: boolean) => {
console.info('data: ' + data);
});
connection.hasDefaultNetSync10+
hasDefaultNetSync(): boolean
Checks whether there is an available network. This API returns the result synchronously.
Required permission: ohos.permission.GET_NETWORK_INFO
System capability: SystemCapability.Communication.NetManager.Core
Return value
| Type | Description |
|---|---|
| boolean | Whether there is an available network. The value true indicates that a network is available, and the value false indicates the opposite. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
let hasDefaultNet = connection.hasDefaultNetSync();
connection.reportNetConnected
reportNetConnected(netHandle: NetHandle, callback: AsyncCallback<void>): void
Reports the network availability to the network management module. This API uses an asynchronous callback to return the result.
NOTE
This API is used by the browser to connect to the portal network. After the network authentication is successful, the browser reports the network connection success to the network management module. The network management module then triggers network detection and updates the network status.
Permission required: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| netHandle | NetHandle | Yes | Network handle. For details, see NetHandle. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the network status is reported successfully, error is undefined. Otherwise, error is an error object. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
connection.reportNetConnected(netHandle, (error: BusinessError) => {
console.error(JSON.stringify(error));
});
});
connection.reportNetConnected
reportNetConnected(netHandle: NetHandle): Promise<void>
Reports that the network is available to the network management module. This API uses a promise to return the result.
Permission required: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| netHandle | NetHandle | Yes | Network handle. For details, see NetHandle. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Network Connection Management Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
connection.reportNetConnected(netHandle).then(() => {
console.info(`report success`);
});
});
connection.reportNetDisconnected
reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback<void>): void
Reports the network unavailability to the network management module. This API uses an asynchronous callback to return the result.
Permission required: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| netHandle | NetHandle | Yes | Network handle. For details, see NetHandle. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the network status is reported successfully, error is undefined. Otherwise, error is an error object. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getDefaultNet((error: BusinessError, netHandle: connection.NetHandle) => {
if (netHandle.netId == 0) {
// If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements.
return;
}
connection.reportNetDisconnected(netHandle, (error: BusinessError, data: void) => {
if (error) {
console.error(`Failed to get default net. Code:${error.code}, message:${error.message}`);
return;
}
console.info("report success");
});
});
connection.reportNetDisconnected
reportNetDisconnected(netHandle: NetHandle): Promise<void>
Reports the network unavailability to the network management module. This API uses a promise to return the result.
Permission required: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| netHandle | NetHandle | Yes | Network handle. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
connection.reportNetDisconnected(netHandle).then( () => {
console.info(`report success`);
});
});
connection.getAddressesByName
getAddressesByName(host: string, callback: AsyncCallback<Array<NetAddress>>): void
Obtains all IP addresses of the default network by resolving the host name. This API uses an asynchronous callback to return the result.
Required permissions: ohos.permission.INTERNET
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| host | string | Yes | Host name to resolve. |
| callback | AsyncCallback<Array<NetAddress>> | Yes | Callback used to return the result. If all IP addresses are successfully obtained, error is undefined, and data is the list of all obtained IP addresses. Otherwise, error is an error object. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getAddressesByName("xxxx", (error: BusinessError, data: connection.NetAddress[]) => {
if (error) {
console.error(`Failed to get addresses. Code:${error.code}, message:${error.message}`);
return;
}
console.info("Succeeded to get data: " + JSON.stringify(data));
});
connection.getAddressesByName
getAddressesByName(host: string): Promise<Array<NetAddress>>
Obtains all IP addresses of the default network by resolving the host name. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| host | string | Yes | Host name to resolve. |
Return value
| Type | Description |
|---|---|
| Promise<Array<NetAddress>> | Promise used to return all IP addresses. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
connection.getAddressesByName("xxxx").then((data: connection.NetAddress[]) => {
console.info("Succeeded to get data: " + JSON.stringify(data));
});
connection.getAddressesByNameWithOptions23+
getAddressesByNameWithOptions(host: string, option?: QueryOptions): Promise<Array<NetAddress>>
Performs the DNS resolution using the current default network based on the specified IP address type. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET
Model constraint: This API can be used only in the stage model.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| host | string | Yes | Host name to resolve. For example, www.example.com. |
| option | QueryOptions | No | Type of the IP address to be queried. The default value is FAMILY_TYPE_ALL. |
Return value
| Type | Description |
|---|---|
| Promise<Array<NetAddress>> | Promise used to return the queried IP address. In the command output, the port field has a fixed value of 0. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let option: connection.QueryOptions = {
family: connection.FamilyType.FAMILY_TYPE_IPV4
};
connection.getAddressesByNameWithOptions("www.example.com", option).then((data: connection.NetAddress[]) => {
console.info(`Succeeded to get data: ${JSON.stringify(data)}`);
}).catch((err: BusinessError) => {
console.error(`get ERROR msg: ${JSON.stringify(err)}`)
});
QueryOptions23+
Defines the type of the IP address to be queried.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| family | FamilyType | No | Yes | Type of the IP address to be queried. The default value is FAMILY_TYPE_ALL. |
FamilyType23+
Indicates the type of the IP address to be queried.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Value | Description |
|---|---|---|
| FAMILY_TYPE_ALL | 0 | All IPv4 and IPv6 addresses are queried. |
| FAMILY_TYPE_IPV4 | 1 | Only IPv4 addresses are queried. |
| FAMILY_TYPE_IPV6 | 2 | Only IPv6 addresses are queried. |
connection.addCustomDnsRule11+
addCustomDnsRule(host: string, ip: Array<string>, callback: AsyncCallback<void>): void
Adds custom DNS rules for the specified host of the current application. This API uses an asynchronous callback to return the result.
NOTE
You can call removeCustomDnsRule to delete a custom DNS rule or call clearCustomDnsRules to delete all custom DNS rules of the current application.
Required permissions: ohos.permission.INTERNET
Atomic service API: This API can be used in atomic services since API version 15.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| host | string | Yes | Name of the custom host. |
| ip | Array<string> | Yes | List of IP addresses mapped to the host name. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the mapping is added successfully, error is undefined. Otherwise, error is an error object. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.addCustomDnsRule("xxxx", ["xx.xx.xx.xx","xx.xx.xx.xx"], (error: BusinessError, data: void) => {
if (error) {
console.error(`Failed to get add custom dns rule. Code:${error.code}, message:${error.message}`);
return;
}
console.info("Succeeded to get data: " + JSON.stringify(data));
})
connection.addCustomDnsRule11+
addCustomDnsRule(host: string, ip: Array<string>): Promise<void>
Adds custom DNS rules for the specified host of the current application. This API uses a promise to return the result.
NOTE
You can call removeCustomDnsRule to delete a custom DNS rule or call clearCustomDnsRules to delete all custom DNS rules of the current application.
Required permissions: ohos.permission.INTERNET
Atomic service API: This API can be used in atomic services since API version 15.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| host | string | Yes | Name of the custom host. |
| ip | Array<string> | Yes | List of IP addresses mapped to the host name. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.addCustomDnsRule("xxxx", ["xx.xx.xx.xx","xx.xx.xx.xx"]).then(() => {
console.info("success");
}).catch((error: BusinessError) => {
console.error(JSON.stringify(error));
})
connection.removeCustomDnsRule11+
removeCustomDnsRule(host: string, callback: AsyncCallback<void>): void
Removes the custom DNS rules of the specified host from the current application. This API uses an asynchronous callback to return the result.
NOTE
You can call addCustomDnsRule to add a custom rule.
Required permissions: ohos.permission.INTERNET
Atomic service API: This API can be used in atomic services since API version 15.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| host | string | Yes | Name of the host for which DNS rules are to be deleted. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the DNS rules are removed successfully, error is undefined. Otherwise, error is an error object. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.removeCustomDnsRule("xxxx", (error: BusinessError, data: void) => {
if (error) {
console.error(`Failed to remove custom dns rule. Code:${error.code}, message:${error.message}`);
return;
}
console.info("Succeeded to get data: " + JSON.stringify(data));
})
connection.removeCustomDnsRule11+
removeCustomDnsRule(host: string): Promise<void>
Removes the custom DNS rules of the specified host from the current application. This API uses a promise to return the result.
NOTE
You can call addCustomDnsRule to add a custom rule.
Required permissions: ohos.permission.INTERNET
Atomic service API: This API can be used in atomic services since API version 15.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| host | string | Yes | Name of the host for which DNS rules are to be deleted. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.removeCustomDnsRule("xxxx").then(() => {
console.info("success");
}).catch((error: BusinessError) => {
console.error(JSON.stringify(error));
})
connection.clearCustomDnsRules11+
clearCustomDnsRules(callback: AsyncCallback<void>): void
Removes all custom DNS rules of the current application. This API uses an asynchronous callback to return the result.
Required permissions: ohos.permission.INTERNET
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If all the DNS rules are removed successfully, error is undefined. Otherwise, error is an error object. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.clearCustomDnsRules((error: BusinessError, data: void) => {
if (error) {
console.error(`Failed to clear custom dns rules. Code:${error.code}, message:${error.message}`);
return;
}
console.info("Succeeded to get data: " + JSON.stringify(data));
})
connection.clearCustomDnsRules11+
clearCustomDnsRules(): Promise<void>
Removes all custom DNS rules of the current application. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET
System capability: SystemCapability.Communication.NetManager.Core
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.clearCustomDnsRules().then(() => {
console.info("success");
}).catch((error: BusinessError) => {
console.error(JSON.stringify(error));
})
connection.setPacFileUrl20+
setPacFileUrl(pacFileUrl: string): void
Sets the URL of the Proxy Auto-Configuration Script (PAC) and enables the PAC proxy capability, for example, http://127.0.0.1:21998/PacProxyScript.pac. You can call findProxyForUrl to parse the URL and obtain the proxy information.
NOTE
- This API can parse scripts and enable the PAC proxy capability on PC/2in120+, Phone23+, Tablet23+ and TV23+ devices. For wearable devices, only the script address is saved, and the PAC proxy capability is not enabled.
- This API does not verify the URL authenticity. If the URL is incorrect when the PAC proxy is enabled, the proxy fails to be enabled and error code 2100002 is returned.
Required permissions: ohos.permission.SET_PAC_URL
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| pacFileUrl | string | Yes | URL of the current PAC script. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100002 | Failed to connect to the service. |
Example
import { connection } from '@kit.NetworkKit';
let pacFileUrl = "http://example.com/proxy.pac";
connection.setPacFileUrl(pacFileUrl);
connection.getPacFileUrl20+
getPacFileUrl(): string
Obtains the URL of the current PAC script.
System capability: SystemCapability.Communication.NetManager.Core
Return value
| Type | Description |
|---|---|
| string | URL of the current PAC script. If no PAC script is available, an empty string is returned. |
Error codes
For details about the error codes, see Network Connection Management Error Codes.
| ID | Error Message |
|---|---|
| 2100002 | Failed to connect to the service. |
Example
import { connection } from '@kit.NetworkKit';
let pacFileUrl = connection.getPacFileUrl();
console.info(pacFileUrl);
connection.findProxyForUrl20+
findProxyForUrl(url: string): string
Parses the specified URL proxy address based on the configured PAC script and returns the corresponding PAC proxy information.
NOTE
- You can use setPacFileUrl or setPacUrl to set the PAC script.
- If no PAC script is set before this interface is called, an empty string is returned.
- The setPacFileUrl API supports parsing scripts and enabling the PAC proxy capability on PC/2in120+, Phone23+, Tablet23+ and TV23+ devices. Therefore, this API can be used to obtain the PAC proxy information on the preceding devices. For wearable devices, this API does not take effect, and an empty string is returned.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| url | string | Yes | URL used to search for the proxy information. |
Return value
| Type | Description |
|---|---|
| string | Proxy information. |
Example
import { connection } from '@kit.NetworkKit';
let proxyInfo = connection.findProxyForUrl("http://example.com");
console.info(proxyInfo);
connection.setPacUrl15+
setPacUrl(pacUrl: string): void
Sets the URL of the system-level Proxy Auto Config (PAC) script.
NOTE
Only the script address can be set. The proxy function cannot be parsed or enabled. To set the script and enable the proxy, call the setPacFileUrl API.
Required permissions: ohos.permission.SET_PAC_URL
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| pacUrl | string | Yes | URL of the PAC script. Note that this URL will not be verified by the API. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
let pacUrl = "xxx";
connection.setPacUrl(pacUrl);
connection.getPacUrl15+
getPacUrl(): string
Obtains the URL of the system-level PAC script.
System capability: SystemCapability.Communication.NetManager.Core
Return value
| Type | Description |
|---|---|
| string | URL of the PAC script. If the PAC script does not exist, error code 2100003 is reported. |
Error codes
For details about the error codes, see Network Connection Management Error Codes.
| ID | Error Message |
|---|---|
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
let pacUrl = connection.getPacUrl();
connection.setNetExtAttribute20+
setNetExtAttribute(netHandle: NetHandle, netExtAttribute: string): Promise<void>
Sets extended attributes of the network specified by netHandle to indicate its security level. This API uses a promise to return the result.
NOTE Currently, this API is available only for PCs.
Required permissions: ohos.permission.SET_NET_EXT_ATTRIBUTE
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| netHandle | NetHandle | Yes | Network handle. |
| netExtAttribute | string | Yes | Extended network attributes. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
if (netHandle.netId == 0) {
// If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements.
return;
}
let netExtAttribute: string = "xxx";
connection.setNetExtAttribute(netHandle, netExtAttribute).then(() => {
console.info("setNetExtAttribute success");
}).catch((error: BusinessError) => {
console.error("setNetExtAttribute failed, err: " + error.code);
})
});
connection.setNetExtAttributeSync20+
setNetExtAttributeSync(netHandle: NetHandle, netExtAttribute: string): void
Sets extended attributes of the network specified by netHandle to indicate its security level. This API returns the result synchronously.
NOTE Currently, this API is available only for PCs.
Required permissions: ohos.permission.SET_NET_EXT_ATTRIBUTE
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| netHandle | NetHandle | Yes | Network handle. |
| netExtAttribute | string | Yes | Extended network attributes. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let netExtAttribute: string = "xxx";
let netHandle = connection.getDefaultNetSync();
if (netHandle.netId != 0) {
connection.setNetExtAttributeSync(netHandle, netExtAttribute);
}
connection.getNetExtAttribute20+
getNetExtAttribute(netHandle: NetHandle): Promise<string>
Obtains the extended attributes of the network specified by netHandle to determine its security level. This API uses a promise to return the result.
Required permission: ohos.permission.GET_NETWORK_INFO
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| netHandle | NetHandle | Yes | Network handle. |
Return value
| Type | Description |
|---|---|
| Promise<string> | Promise used to return the network extension attributes. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
if (netHandle.netId == 0) {
// If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements.
return;
}
connection.getNetExtAttribute(netHandle).then((netExtAttribute: string) => {
console.info("getNetExtAttribute: " + netExtAttribute);
}).catch((error: BusinessError) => {
console.error("getNetExtAttribute failed, err: " + error.code);
})
});
connection.getNetExtAttributeSync20+
getNetExtAttributeSync(netHandle: NetHandle): string
Obtains the extended attributes of the network specified by netHandle to determine its security level. This API returns the result synchronously.
Required permission: ohos.permission.GET_NETWORK_INFO
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| netHandle | NetHandle | Yes | Network handle. |
Return value
| Type | Description |
|---|---|
| string | Extended network attributes. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let netHandle = connection.getDefaultNetSync();
if (netHandle.netId != 0) {
let netExtAttribute: string = connection.getNetExtAttributeSync(netHandle);
console.info("getNetExtAttribute: " + netExtAttribute);
}
connection.getIpNeighTable22+
getIpNeighTable(): Promise<Array<NetIpMacInfo>>
Obtains information about entries in the IP neighbor table of the local device, including IPv4 and IPv6 entries. Each entry contains an IP address, a MAC address, and a network adapter name. This API uses a promise to return the result.
NOTE
This interface is used to obtain the cached data of the IP neighbor table, not the data of all connections on the LAN.
This API is used to check network exceptions and parse the mapping between IP addresses and MAC addresses.
Required permissions: ohos.permission.GET_NETWORK_INFO and ohos.permission.GET_IP_MAC_INFO
System capability: SystemCapability.Communication.NetManager.Core
Return value
| Type | Description |
|---|---|
| Promise<Array<NetIpMacInfo>> | Promise used to return information about entries in the IP neighbor table. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getIpNeighTable().then((data: connection.NetIpMacInfo[]) => {
if (data.length !== 0) {
console.info(`ipAddress:${data[0].ipAddress}`);
console.info(`ifaceName:${data[0].iface}`);
console.info(`macAddress:${data[0].macAddress}`);
}
}).catch((error: BusinessError) => {
console.error(`error fetching ip neigh table. Code:${error.code}, message:${error.message}`);
});
connection.getConnectOwnerUid23+
getConnectOwnerUid(protocol: ProtocolType, local: NetAddress, remote: NetAddress): Promise<number>
Queries the UID of the application that initiates a specified network connection. This API uses a promise to return the result.
NOTE
- This API can be called only in VPN applications.
- Set the port numbers of the local and remote parameters when calling the API. If the port number is not set or is set to 0, the API filters out a set of UIDs that meet the conditions based on other parameters and returns a matched UID.
- When protocol is set to PROTO_TYPE_UDP, if no UID is found based on the local and remote parameters, the UID is filtered based on the local parameter and the matched UID is returned.
Required permission: ohos.permission.GET_NETWORK_INFO
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| protocol | ProtocolType | Yes | Type of a network protocol. |
| local | NetAddress | Yes | Source network address. |
| remote | NetAddress | Yes | Destination network address. |
Return value
| Type | Description |
|---|---|
| Promise<number> | Promise used to return the UID of an application. If no matching UID is found, -1 is returned. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100301 | Incorrect usage in non-VPN application. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let protocol = connection.ProtocolType.PROTO_TYPE_TCP;
let local: connection.NetAddress = { address: '192.168.1.100', family: 1, port: 6666 };
let remote: connection.NetAddress = { address: '192.168.1.200', family: 1, port: 8888 };
connection.getConnectOwnerUid(protocol, local, remote).then((uid) => {
console.info(`uid: ${uid}`);
}).catch((error: BusinessError) => {
console.error(`getConnectOwnerUid failed. errorCode: ${error.code} message:${error.message}`);
});
connection.getConnectOwnerUidSync23+
getConnectOwnerUidSync(protocol: ProtocolType, local: NetAddress, remote: NetAddress): number
Queries the UID of the application that initiates a specified network connection. This API returns the result synchronously.
NOTE
- This API can be called only in VPN applications.
- Set the port numbers of the local and remote parameters when calling the API. If the port number is not set or is set to 0, the API filters out a set of UIDs that meet the conditions based on other parameters and returns a matched UID.
- When protocol is set to PROTO_TYPE_UDP, if no UID is found based on the local and remote parameters, the UID is filtered based on the local parameter and the matched UID is returned.
Required permission: ohos.permission.GET_NETWORK_INFO
System capability: SystemCapability.Communication.NetManager.Core
Model restriction: This API can be used only in the stage model.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| protocol | ProtocolType | Yes | Type of a network protocol. |
| local | NetAddress | Yes | Source network address. |
| remote | NetAddress | Yes | Destination network address. |
Return value
| Type | Description |
|---|---|
| number | UID of an application. If no matching UID is found, -1 is returned. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100301 | Incorrect usage in non-VPN application. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let protocol = connection.ProtocolType.PROTO_TYPE_TCP;
let local: connection.NetAddress = { address: '192.168.1.100', family: 1, port: 6666 };
let remote: connection.NetAddress = { address: '192.168.1.200', family: 1, port: 8888 };
try {
let uid = connection.getConnectOwnerUidSync(protocol, local, remote);
console.info(`uid: ${uid}`);
} catch (e) {
let err = e as BusinessError;
console.error(`getConnectOwnerUid failed. errorCode: ${err.code} message:${err.message}`);
}
connection.getDnsAscii23+
getDnsAscii(host: string, flag?: ConversionProcess): string
Converts the host name from Unicode to ASCII and controls the conversion behavior through the optional conversion process parameter (conversionProcess).
NOTE
If conversionProcess is set to NO_CONFIGURATION, only the domain names corresponding to the Unicode characters that have been officially allocated can be converted.
When conversionProcess is set to ALLOW_UNASSIGNED, domain names that contain Unicode characters that have not been assigned meanings can be converted.
If conversionProcess is set to USE_STD3_ASCII_RULES, the generated ASCII domain name is forcibly checked based on the STD-3 ASCII rule (RFC 1123 standard) during the conversion.
Digits and English letters in the input parameters are not transcoded.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| host | string | Yes | Host name to be converted. The length of each label (separated by dots) cannot exceed 63 bytes. |
| flag | ConversionProcess | No | Conversion flow parameter. The default value is NO_CONFIGURATION. |
Return value
| Type | Description |
|---|---|
| string | Conversion result. |
Error codes
For details about the error codes, see Network Connection Management Error Codes.
| ID | Error Message |
|---|---|
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
let result = connection.getDnsAscii("www.example.com," connection.ConversionProcess.NO_CONFIGURATION);
console.info(result); // Expected result: www.xn--fsq092h.com
let result = connection.getDnsAscii("www.example.com", connection.ConversionProcess.NO_CONFIGURATION);
console.info(result); // Expected result: www.example.com
connection.getDnsUnicode23+
getDnsUnicode(host: string, flag?: ConversionProcess): string
Converts host names from ASCII to Unicode using the Punycode encoding mode and uses the optional conversionProcess parameter to control the conversion behavior.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| host | string | Yes | Host name to be converted. |
| flag | ConversionProcess | No | Conversion flow parameter. The default value is NO_CONFIGURATION. |
Return value
| Type | Description |
|---|---|
| string | Conversion result. |
Error codes
For details about the error codes, see Network Connection Management Error Codes.
| ID | Error Message |
|---|---|
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
let result = connection.getDnsUnicode("www.xn--fsq092h.com", connection.ConversionProcess.NO_CONFIGURATION);
console.info(result); // Expected result: www.example.com
let result = connection.getDnsUnicode("www.example.com", connection.ConversionProcess.NO_CONFIGURATION);
console.info(result); // Expected result: www.example.com
connection.getSystemNetPortStates24+
getSystemNetPortStates(): Promise<NetPortStatesInfo>
Obtains information about all TCP and UDP ports currently listened by the system, and the PID and UID of the processes that listen for the ports. Both IPv4 and IPv6 addresses are supported.
NOTE
This API is used to obtain information about the TCP and UDP ports currently listened by the system. The detailed fields are as follows:
TCP port fields: local address, local port, remote address, remote port, TCP connection status, process PID, and process UID
UDP port fields: local address, local port, process PID, and process UID
Required permissions: ohos.permission.GET_IP_MAC_INFO
Model constraint: This API can be used only in the stage model.
System capability: SystemCapability.Communication.NetManager.Core
Return value
| Type | Description |
|---|---|
| Promise<NetPortStatesInfo> | Promise used to return the TCP and UDP port information. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getSystemNetPortStates().then((data: connection.NetPortStatesInfo) => {
console.info(`Succeeded to get data: ${JSON.stringify(data)}`);
if (data.tcpPortStatesInfo?.length) {
data.tcpPortStatesInfo?.forEach(item => {
console.info(`Succeeded to get Tcp data: ${JSON.stringify(item)}`);
})
} else {
console.info("TcpPortStatesInfo is undefined ");
}
if (data.udpPortStatesInfo?.length) {
data.udpPortStatesInfo?.forEach(item => {
console.info(`Succeeded to get Udp data: ${JSON.stringify(item)}`);
})
} else {
console.info("UdpPortStatesInfo is undefined ");
}
}).catch((error: BusinessError) => {
console.error(`Error fetching getSystemNetPortStates. Code:${error.code}, message:${error.message}`);
});
connection.queryTraceRoute
queryTraceRoute(destination: string, option?: TraceRouteOptions): Promise<TraceRouteInfo[]>
Queries the network route tracing information. This API uses a promise to return the result.
NOTE
To call this API, the application needs to apply for the precise location permission. According to Applying for Location Permissions (ArkTS), the caller needs to apply for both ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION.
Since: 26.0.0
Required permissions: ohos.permission.INTERNET, ohos.permission.ACCESS_NET_TRACE_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION
Model constraint: This API can be used only in the stage model.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| destination | string | Yes | Target domain name or IP address, for example, www.example.com or 8.8.8.8. |
| option | TraceRouteOptions | No | Options for route tracing. If this parameter is not specified, the default configuration is used. |
Return value
| Type | Description |
|---|---|
| Promise<TraceRouteInfo[]> | Promise used to return the array of route tracing information. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100001 | Invalid parameter value. |
| 2100003 | Internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let dest: string = "www.example.com";
let options: connection.TraceRouteOptions = {
maxJumpNumber: 30,
packetsType: connection.PacketsType.NETCONN_PACKETS_ICMP
};
connection.queryTraceRoute(dest, options).then((data: connection.TraceRouteInfo[]) => {
console.info(JSON.stringify(data));
}).catch((err: BusinessError) => {
console.error(JSON.stringify(err));
});
connection.queryProbeResult
queryProbeResult(destination: string, duration: number): Promise<ProbeResultInfo>
Queries network probe results. If an exception (for example, network disconnection) occurs and the request fails to be sent, the API immediately returns the result without performing subsequent probe. This API uses a promise to return the result.
NOTE
This API is used to perform network probe on a target host for a period of time to obtain the packet loss rate and RTT information.
Since: 26.0.0
Required permissions: ohos.permission.INTERNET
System capability: SystemCapability.Communication.NetManager.Core
Model restriction: This API can be used only in the stage model.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| destination | string | Yes | Target domain name or IP address, for example, www.example.com or 8.8.8.8. |
| duration | number | Yes | Probe duration, in seconds. The value range is [1, 1000]. The probe interval is one second. If no exception (such as network disconnection) occurs, the probe result is returned when the probe duration expires. This field indicates the total probe duration. If the value is too large, application thread resources may be occupied for a long time. |
Return value
| Type | Description |
|---|---|
| Promise<ProbeResultInfo> | Promise used to return the probe result. |
Error codes For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100001 | Invalid parameter value. |
| 2100003 | Internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let dest: string = "www.example.com";
let duration: number = 10;
connection.queryProbeResult(dest, duration).then((data: connection.ProbeResultInfo) => {
console.info(`LossRate: ${data.lossRate}, RTT: ${data.rtt}`);
}).catch((err: BusinessError) => {
console.error(JSON.stringify(err));
});
NetConnection
Represents the network connection object type.
NOTE
(1) When the network transitions from unavailable to available, the netAvailable, netCapabilitiesChange, and netConnectionPropertiesChange events are triggered.
(2) If the network transitions from available to unavailable after a netAvailable event is received, a netLost event is triggered.
(3) If no netAvailable event is received, a netUnavailable event is directly triggered.
(4) When the network transitions from Wi-Fi to cellular, a netLost event is first triggered to indicate that the Wi-Fi network is lost and then a netAvailable event is triggered to indicate that the cellular network is available.
register
register(callback: AsyncCallback<void>): void
Registers a listener for network status changes. To listen for a specific type of events, call on to enable listening and then call register to register an event listener.
NOTE
After using the register API, you need to call unregister to deregister the listener.
Required permission: ohos.permission.GET_NETWORK_INFO
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If a listener for network status changes is registered successfully, error is undefined. Otherwise, error is an error object. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
| 2101008 | The callback already exists. |
| 2101022 | The number of requests exceeded the maximum allowed. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let netCon: connection.NetConnection = connection.createNetConnection();
netCon.register((error: BusinessError) => {
console.error(JSON.stringify(error));
});
unregister
unregister(callback: AsyncCallback<void>): void
Unregisters the listener for network status changes.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If a listener for network status changes is unregistered successfully, error is undefined. Otherwise, error is an error object. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
| 2101007 | The callback does not exist. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
let netCon: connection.NetConnection = connection.createNetConnection();
netCon.unregister((error: BusinessError) => {
console.error(JSON.stringify(error));
});
on('netAvailable')
on(type: 'netAvailable', callback: Callback<NetHandle>): void
Registers a listener for netAvailable events. Before you call this API, make sure that you have called register to add a listener for network status changes. When the listener is no longer needed, call unregister to remove it.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. This field has a fixed value of netAvailable. netAvailable: event indicating that the data network is available. |
| callback | Callback<NetHandle> | Yes | Callback used to return the network handle. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
// Create a NetConnection object.
let netCon: connection.NetConnection = connection.createNetConnection();
// Use the on API to enable listening for netAvailable events.
netCon.on('netAvailable', (data: connection.NetHandle) => {
console.info("Succeeded to get data: " + JSON.stringify(data));
});
// Register a listener for network status change events. This API must be called after the on API.
netCon.register((error: BusinessError) => {
console.error(JSON.stringify(error));
});
// Use the unregister API to unsubscribe from netAvailable events.
netCon.unregister((error: BusinessError) => {
console.error(JSON.stringify(error));
});
on('netBlockStatusChange')
on(type: 'netBlockStatusChange', callback: Callback<NetBlockStatusInfo>): void
Registers a listener for netBlockStatusChange events. Before you call this API, make sure that you have called register to add a listener for network status changes. When the listener is no longer needed, call unregister to remove it.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. This field has a fixed value of netBlockStatusChange. netBlockStatusChange: event indicating a change in the network blocking status. |
| callback | Callback<NetBlockStatusInfo> | Yes | Callback used to return the result. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
// Create a NetConnection object.
let netCon: connection.NetConnection = connection.createNetConnection();
// Use the on API to enable listening for netBlockStatusChange events.
netCon.on('netBlockStatusChange', (data: connection.NetBlockStatusInfo) => {
console.info("Succeeded to get data: " + JSON.stringify(data));
});
// Register a listener for network status change events. This API must be called after the on API.
netCon.register((error: BusinessError) => {
console.error(JSON.stringify(error));
});
// Use the unregister API to remove the listener for netBlockStatusChange events.
netCon.unregister((error: BusinessError) => {
console.error(JSON.stringify(error));
});
on('netCapabilitiesChange')
on(type: 'netCapabilitiesChange', callback: Callback<NetCapabilityInfo>): void
Registers a listener for netCapabilitiesChange events. Before you call this API, make sure that you have called register to add a listener for network status changes. When the listener is no longer needed, call unregister to remove it.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. This field has a fixed value of netCapabilitiesChange. netCapabilitiesChange: event indicating that the network capabilities have changed. |
| callback | Callback<NetCapabilityInfo> | Yes | Callback used to return the network handle (netHandle) and capability information (netCap). |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
// Create a NetConnection object.
let netCon: connection.NetConnection = connection.createNetConnection();
// Use the on API to enable listening for netCapChange events.
netCon.on('netCapabilitiesChange', (data: connection.NetCapabilityInfo) => {
console.info("Succeeded to get data: " + JSON.stringify(data));
});
// Register a listener for network status change events. This API must be called after the on API.
netCon.register((error: BusinessError) => {
console.error(JSON.stringify(error));
});
// Unsubscribe from netCapabilitiesChange events.
netCon.unregister((error: BusinessError) => {
console.error(JSON.stringify(error));
});
on('netConnectionPropertiesChange')
on(type: 'netConnectionPropertiesChange', callback: Callback<NetConnectionPropertyInfo>): void
Registers a listener for netConnectionPropertiesChange events. Before you call this API, make sure that you have called register to add a listener for network status changes. When the listener is no longer needed, call unregister to remove it.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. This field has a fixed value of netConnectionPropertiesChange. netConnectionPropertiesChange: event indicating that network connection properties have changed. |
| callback | Callback<NetConnectionPropertyInfo> | Yes | Callback used to return the result. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
// Create a NetConnection object.
let netCon: connection.NetConnection = connection.createNetConnection();
// Use the on API to enable listening for netConnectionChange events.
netCon.on('netConnectionPropertiesChange', (data: connection.NetConnectionPropertyInfo) => {
console.info("Succeeded to get data: " + JSON.stringify(data));
});
// Register a listener for network status change events. This API must be called after the on API.
netCon.register((error: BusinessError) => {
console.error(JSON.stringify(error));
});
// Use the unregister API to remove the listener for netConnectionPropertiesChange events.
netCon.unregister((error: BusinessError) => {
console.error(JSON.stringify(error));
});
on('netLost')
on(type: 'netLost', callback: Callback<NetHandle>): void
Registers a listener for netLost events. Before you call this API, make sure that you have called register to add a listener for network status changes. When the listener is no longer needed, call unregister to remove it.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. This field has a fixed value of netLost. netLost: event indicating that the network is interrupted or normally disconnected. |
| callback | Callback<NetHandle> | Yes | Callback used to return the result, which is a netHandle object. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
// Create a NetConnection object.
let netCon: connection.NetConnection = connection.createNetConnection();
// Use the on API to enable listening for netLost events.
netCon.on('netLost', (data: connection.NetHandle) => {
console.info("Succeeded to get data: " + JSON.stringify(data));
});
// Register a listener for network status change events. This API must be called after the on API.
netCon.register((error: BusinessError) => {
console.error(JSON.stringify(error));
});
// Use the unregister API to remove the listener for netLost events.
netCon.unregister((error: BusinessError) => {
console.error(JSON.stringify(error));
});
on('netUnavailable')
on(type: 'netUnavailable', callback: Callback<void>): void
Registers a listener for netUnavailable events. Before you call this API, make sure that you have called register to add a listener for network status changes. When the listener is no longer needed, call unregister to remove it.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. This field has a fixed value of netUnavailable. netUnavailable: event indicating that the network is unavailable. |
| callback | Callback<void> | Yes | Callback used to return the result, which is empty. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
// Create a NetConnection object.
let netCon: connection.NetConnection = connection.createNetConnection();
// Use the on API to enable listening for netUnavailable events.
netCon.on('netUnavailable', () => {
console.info("Succeeded to get unavailable net event");
});
// Register a listener for network status change events. This API must be called after the on API.
netCon.register((error: BusinessError) => {
console.error(JSON.stringify(error));
});
// Use the unregister API to remove the listener for netUnavailable events.
netCon.unregister((error: BusinessError) => {
console.error(JSON.stringify(error));
});
NetHandle
Represents the network handle.
Before invoking NetHandle APIs, call getNetHandle to obtain a NetHandle object. For example, you can call getDefaultNet to obtain the network handle of the default network.
System capability: SystemCapability.Communication.NetManager.Core
Attributes
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| netId | number | No | No | Network ID. The value 0 indicates that there is no default network. The other valid values must be greater than or equal to 100. Atomic service API: This API can be used in atomic services since API version 11. |
bindSocket9+
bindSocket(socketParam: TCPSocket | UDPSocket, callback: AsyncCallback<void>): void
Binds the TCPSocket or UDPSocket to the network specified by NetHandle. This API uses an asynchronous callback to return the result.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| socketParam | TCPSocket | UDPSocket | Yes | TCPSocket or UDPSocket object. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the TCPSocket or UDPSocket object is successfully bound to the current network, error is undefined. Otherwise, error is an error object. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection, socket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
interface Data {
message: ArrayBuffer,
remoteInfo: socket.SocketRemoteInfo
}
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
if (netHandle.netId == 0) {
// If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements.
}
let tcp : socket.TCPSocket = socket.constructTCPSocketInstance();
let udp : socket.UDPSocket = socket.constructUDPSocketInstance();
let socketType = "TCPSocket";
if (socketType == "TCPSocket") {
tcp.bind({address:"192.168.xxx.xxx",
port:8080,
family:1} as socket.NetAddress, (error: Error) => {
if (error) {
console.error('bind fail');
return;
}
netHandle.bindSocket(tcp, (error: BusinessError, data: void) => {
if (error) {
console.error(`Failed to bind socket. Code:${error.code}, message:${error.message}`);
return;
} else {
console.info(JSON.stringify(data));
}
});
});
} else {
let callback: (value: Data) => void = (value: Data) => {
console.info("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
};
udp.bind({address:"192.168.xxx.xxx",
port:8080,
family:1} as socket.NetAddress, (error: BusinessError) => {
if (error) {
console.error(`Failed to bind. Code:${error.code}, message:${error.message}`);
return;
}
udp.on('message', (data: Data) => {
console.info("Succeeded to get data: " + JSON.stringify(data));
});
netHandle.bindSocket(udp, (error: BusinessError, data: void) => {
if (error) {
console.error(`Failed to bind socket. Code:${error.code}, message:${error.message}`);
return;
} else {
console.info(JSON.stringify(data));
}
});
});
}
})
bindSocket9+
bindSocket(socketParam: TCPSocket | UDPSocket): Promise<void>
Binds the TCPSocket or UDPSocket to the network specified by NetHandle. This API uses a promise to return the result.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| socketParam | TCPSocket | UDPSocket | Yes | TCPSocket or UDPSocket object. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection, socket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
interface Data {
message: ArrayBuffer,
remoteInfo: socket.SocketRemoteInfo
}
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
if (netHandle.netId == 0) {
// If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements.
return;
}
let tcp : socket.TCPSocket = socket.constructTCPSocketInstance();
let udp : socket.UDPSocket = socket.constructUDPSocketInstance();
let socketType = "TCPSocket";
if (socketType == "TCPSocket") {
tcp.bind({address:"192.168.xxx.xxx",
port:8080,
family:1} as socket.NetAddress, (error: Error) => {
if (error) {
console.error('bind fail');
return;
}
netHandle.bindSocket(tcp).then(() => {
console.info("bind socket success");
}).catch((error: BusinessError) => {
console.error(`Failed to bind socket. Code:${error.code}, message:${error.message}`);
});
});
} else {
let callback: (value: Data) => void = (value: Data) => {
console.info("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
udp.bind({address:"192.168.xxx.xxx",
port:8080,
family:1} as socket.NetAddress, (error: BusinessError) => {
if (error) {
console.error(`Failed to bind. Code:${error.code}, message:${error.message}`);
return;
}
udp.on('message', (data: Data) => {
console.info("Succeeded to get data: " + JSON.stringify(data));
});
netHandle.bindSocket(udp).then(() => {
console.info("bind socket success");
}).catch((error: BusinessError) => {
console.error(`Failed to bind socket. Code:${error.code}, message:${error.message}`);
});
});
}
});
getAddressesByName
getAddressesByName(host: string, callback: AsyncCallback<Array<NetAddress>>): void
Obtains all IP addresses by using the network specified by NetHandle to resolve the host name. This API uses an asynchronous callback to return the result.
Atomic service API: This API can be used in atomic services since API version 15.
Required permissions: ohos.permission.INTERNET
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| host | string | Yes | Host name to resolve. For example, www.example.com. |
| callback | AsyncCallback<Array<NetAddress>> | Yes | Callback used to return the result. If all IP addresses are successfully obtained, error is undefined, and data is the list of all obtained IP addresses. Otherwise, error is an error object. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
if (netHandle.netId == 0) {
// If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements.
return;
}
let host = "www.example.com";
netHandle.getAddressesByName(host, (error: BusinessError, data: connection.NetAddress[]) => {
if (error) {
console.error(`Failed to get addresses. Code:${error.code}, message:${error.message}`);
return;
}
console.info("Succeeded to get data: " + JSON.stringify(data));
});
});
getAddressesByName
getAddressesByName(host: string): Promise<Array<NetAddress>>
Obtains all IP addresses by using the network specified by NetHandle to resolve the host name. This API uses a promise to return the result.
Atomic service API: This API can be used in atomic services since API version 15.
Required permissions: ohos.permission.INTERNET
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| host | string | Yes | Host name to resolve. For example, www.example.com. |
Return value
| Type | Description |
|---|---|
| Promise<Array<NetAddress>> | Promise used to return all IP addresses. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
if (netHandle.netId == 0) {
// If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements.
return;
}
let host = "www.example.com";
netHandle.getAddressesByName(host).then((data: connection.NetAddress[]) => {
console.info("Succeeded to get data: " + JSON.stringify(data));
});
});
getAddressesByNameWithOptions23+
getAddressesByNameWithOptions(host: string, option?: QueryOptions): Promise<Array<NetAddress>>
Performs DNS resolution using the network specified by NetHandle based on the specified IP address type. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET
Model constraint: This API can be used only in the stage model.
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| host | string | Yes | Host name to resolve. For example, www.example.com. |
| option | QueryOptions | No | Type of the IP address to be queried. |
Return value
| Type | Description |
|---|---|
| Promise<Array<NetAddress>> | Promise used to return the queried IP address. In the command output, the port field has a fixed value of 0. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
if (netHandle.netId == 0) {
// If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements.
return;
}
let host = "www.example.com";
let option: connection.QueryOptions = {
family: connection.FamilyType.FAMILY_TYPE_IPV4
};
netHandle.getAddressesByNameWithOptions(host, option).then((data: connection.NetAddress[]) => {
console.info(`Succeeded to get data: ${JSON.stringify(data)}`);
}).catch((err: BusinessError) => {
console.error(`get ERROR msg: ${JSON.stringify(err)}`)
});
});
getAddressByName
getAddressByName(host: string, callback: AsyncCallback<NetAddress>): void
Obtains the first IP address by using the network specified by NetHandle to resolve the host name. This API uses an asynchronous callback to return the result.
Required permissions: ohos.permission.INTERNET
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| host | string | Yes | Host name to resolve. For example, www.example.com. |
| callback | AsyncCallback<NetAddress> | Yes | Callback used to return the result. If the first IP address is obtained successfully, error is undefined, and data is the first obtained IP address. Otherwise, error is an error object. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
if (netHandle.netId == 0) {
// If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements.
return;
}
let host = "www.example.com";
netHandle.getAddressByName(host, (error: BusinessError, data: connection.NetAddress) => {
if (error) {
console.error(`Failed to get address. Code:${error.code}, message:${error.message}`);
return;
}
console.info("Succeeded to get data: " + JSON.stringify(data));
});
});
getAddressByName
getAddressByName(host: string): Promise<NetAddress>
Obtains the first IP address by using the network specified by NetHandle to resolve the host name. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET
System capability: SystemCapability.Communication.NetManager.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| host | string | Yes | Host name to resolve. For example, www.example.com. |
Return value
| Type | Description |
|---|---|
| Promise<NetAddress> | Promise used to return the first IP address. |
Error codes
For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Failed to connect to the service. |
| 2100003 | System internal error. |
Example
import { connection } from '@kit.NetworkKit';
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
if (netHandle.netId == 0) {
// If no network is connected, the obtained netId of netHandle is 0, which is abnormal. You can add specific processing based on the service requirements.
return;
}
let host = "www.example.com";
netHandle.getAddressByName(host).then((data: connection.NetAddress) => {
console.info("Succeeded to get data: " + JSON.stringify(data));
});
});
NetCap
Defines the network capability.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Value | Description |
|---|---|---|
| NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages. Atomic service API: This API can be used in atomic services since API version 11. |
| NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered. Atomic service API: This API can be used in atomic services since API version 11. |
| NET_CAPABILITY_INTERNET | 12 | The network is capable of Internet access but the network connectivity is not successfully verified by the network management module. This capability is configured by the network provider. Your application can determine the network connectivity by NET_CAPABILITY_VALIDATED and NET_CAPABILITY_CHECKING_CONNECTIVITY. Atomic service API: This API can be used in atomic services since API version 11. |
| NET_CAPABILITY_NOT_VPN | 15 | The network does not use a virtual private network (VPN). Atomic service API: This API can be used in atomic services since API version 11. |
| NET_CAPABILITY_VALIDATED | 16 | The network management module successfully connects to the Huawei Cloud address through this network. This capability is configured by the network management module. Note: If the network management module fails to connect to the Huawei Cloud address, this flag is not available in the network capability, but this does not mean a complete loss in Internet access. Note that for a newly connected network, this value may not reflect the actual verification result as network connectivity verification is in progress. Your application can use NET_CAPABILITY_CHECKING_CONNECTIVITY12+ to check whether network connectivity verification is in progress. Atomic service API: This API can be used in atomic services since API version 11. |
| NET_CAPABILITY_PORTAL12+ | 17 | The network is found to have a captive portal and user login authentication is required. This capability is set by the connection management module. Atomic service API: This API can be used in atomic services since API version 12. |
| NET_CAPABILITY_CHECKING_CONNECTIVITY12+ | 31 | The network management module is verifying the network connectivity. This flag remains valid until the network connectivity check is complete. During this period, the value of NET_CAPABILITY_VALIDATED may be incorrect. After the network connectivity check is complete, this flag is cleared and your application can determine the network connectivity by checking NET_CAPABILITY_VALIDATED. Atomic service API: This API can be used in atomic services since API version 12. |
NetBearType
Enumerates network types.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Value | Description |
|---|---|---|
| BEARER_CELLULAR | 0 | Cellular network. Atomic service API: This API can be used in atomic services since API version 11. |
| BEARER_WIFI | 1 | Wi-Fi network. Atomic service API: This API can be used in atomic services since API version 11. |
| BEARER_BLUETOOTH12+ | 2 | Bluetooth network. Atomic service API: This API can be used in atomic services since API version 12. |
| BEARER_ETHERNET | 3 | Ethernet network. Atomic service API: This API can be used in atomic services since API version 11. |
| BEARER_VPN12+ | 4 | VPN. |
ConversionProcess23+
Enumerates the parameters of the ASCII/Unicode transcoding process.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Value | Description |
|---|---|---|
| NO_CONFIGURATION | 0 | Only domain names with assigned Unicode code points can be converted. (Unicode assigns a unique number to each character. This number is called a code point.) |
| ALLOW_UNASSIGNED | 1 | Allows the translation of domain names that contain unassigned Unicode code points (in a Unicode character set, not all code points are assigned characters, i.e., unassigned Unicode code points). |
| USE_STD3_ASCII_RULES | 2 | During the conversion, the STD-3 ASCII rule (RFC 1123 standard) is forcibly used to check the generated ASCII domain name. |
TcpState24+
Enumerates TCP states.
Model constraint: This API can be used only in the stage model.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Value | Description |
|---|---|---|
| TCP_ESTABLISHED | 1 | The connection is established, and data can be sent and received properly. |
| TCP_SYN_SENT | 2 | The client sends SYN and waits for ACK+SYN from the server (the first step of the three-way handshake). |
| TCP_SYN_RECV | 3 | The server receives SYN and sends ACK+SYN, and waits for ACK from the client (the second step of the three-way handshake). |
| TCP_FIN_WAIT1 | 4 | The active end sends FIN and waits for ACK from the peer end. |
| TCP_FIN_WAIT2 | 5 | The active end receives ACK of FIN and waits for ACK from the peer end. |
| TCP_TIME_WAIT | 6 | The active end receives FIN from the peer end and replies with ACK. After two times of the maximum segment lifetime, the connection is completely released. |
| TCP_CLOSE | 7 | Initial/closed state, with no connection. |
| TCP_CLOSE_WAIT | 8 | The passive end receives FIN and sends ACK, and waits for FIN from the peer end. |
| TCP_LAST_ACK | 9 | The passive end sends FIN and waits for ACK from the peer end. |
| TCP_LISTEN | 10 | The server listens and waits for the client to connect. |
| TCP_CLOSING | 11 | Both ends send FIN and wait for ACK from each other. |
PacketsType
Defines the type of network probe data packets.
Since: 26.0.0
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Value | Description |
|---|---|---|
| NETCONN_PACKETS_ICMP | 0 | ICMP packet type. |
| NETCONN_PACKETS_UDP | 1 | UDP packet type. |
HttpProxy10+
Represents the HTTP proxy configuration.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| host | string | No | No | Host name of the proxy server. Atomic service API: This API can be used in atomic services since API version 11. |
| port | number | No | No | Host port. The value range is [0, 65535]. Atomic service API: This API can be used in atomic services since API version 11. |
| exclusionList | Array<string> | No | No | List of the names of hosts that do not use a proxy. Host names can be domain names, IP addresses, or wildcards. The detailed matching rules are as follows: - Domain name matching: - Exact match: The host name of the proxy server exactly matches any host name in the list. - Partial match: The host name of the proxy server contains any host name in the list. For example, if ample.com is set in the host name list, ample.com, www.ample.com, and ample.com:80 are matched, and www.example.com and ample.com.org are not matched. - IP address matching: The host name of the proxy server exactly matches any IP address in the list. - Both the domain name and IP address are added to the list for matching. - A single asterisk (*) is the only valid wildcard. If the list contains only wildcards, the wildcards match all host names; that is, the HTTP proxy is disabled. A wildcard can only be added independently. It cannot be added to the list together with other domain names or IP addresses. Otherwise, the wildcard does not take effect. - Host names are case insensitive. - Protocol prefixes such as http and https are ignored during matching. Atomic service API: This API can be used in atomic services since API version 11. |
| username12+ | string | No | Yes | Name of the user who uses the proxy. Note: This parameter takes effect only when the password parameter is set. |
| password12+ | string | No | Yes | Password of the user who uses the proxy. Note: The setting takes effect only when the username parameter is set. |
NetSpecifier
Provides an instance that bears data network capabilities.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| netCapabilities | NetCapabilities | No | No | Network transmission capabilities and bearer types of the data network. |
| bearerPrivateIdentifier | string | No | Yes | Network identifier. The identifier of the cellular network is slot0 for SIM card 1 and slot1 for SIM card 2. Since API version 12, you can pass the registered WLAN hotspot to the API to specify the WLAN network to be activated. |
Example
import { connection } from '@kit.NetworkKit';
import { wifiManager } from '@kit.ConnectivityKit';
import { BusinessError } from '@kit.BasicServicesKit';
let config: wifiManager.WifiDeviceConfig = {
ssid: "TEST",
preSharedKey: "**********",
securityType: wifiManager.WifiSecurityType.WIFI_SEC_TYPE_PSK
};
// Obtain the network ID of the registered WLAN through wifiManager.addCandidateConfig.
wifiManager.addCandidateConfig(config,(error,networkId) => {
let netConnectionWlan = connection.createNetConnection({
netCapabilities: {
bearerTypes: [connection.NetBearType.BEARER_WIFI]
},
bearerPrivateIdentifier: `${networkId}`
});
netConnectionWlan.register((error: BusinessError) => {
console.error(JSON.stringify(error));
});
});
NetCapabilityInfo10+
Provides an instance that bears data network capabilities.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| netHandle | NetHandle | No | No | Network handle. |
| netCap | NetCapabilities | No | No | Network transmission capabilities and bearer types of the data network. |
NetCapabilities
Defines the network capability set.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| linkUpBandwidthKbps | number | No | Yes | Uplink (device-to-network) bandwidth, in kbit/s. The value 0 indicates that the current network bandwidth cannot be evaluated. |
| linkDownBandwidthKbps | number | No | Yes | Downlink (network-to-device) bandwidth, in kbit/s. The value 0 indicates that the current network bandwidth cannot be evaluated. |
| networkCap | Array<NetCap> | No | Yes | Network capability. Atomic service API: This API can be used in atomic services since API version 11. |
| bearerTypes | Array<NetBearType> | No | No | Network type. The array contains only one network type. Atomic service API: This API can be used in atomic services since API version 11. |
NetConnectionPropertyInfo11+
Defines the network connection properties.
System capability: SystemCapability.Communication.NetManager.Core
Attributes
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| netHandle | NetHandle | No | No | Network handle. |
| connectionProperties | ConnectionProperties | No | No | Defines the network connection properties. |
NetBlockStatusInfo11+
Obtains the network block status information.
System capability: SystemCapability.Communication.NetManager.Core
Attributes
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| netHandle | NetHandle | No | No | Network handle. |
| blocked | boolean | No | No | Whether the current network is blocked. The value true indicates that the network is congested, and the value false indicates the opposite. |
ConnectionProperties
Defines the network connection properties.
NOTE
The values of linkAddresses, routes, and dnses may be empty. You need to protect the empty values. You are advised to check whether the objects exist before using the values.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| interfaceName | string | No | No | Network interface card (NIC) name. |
| domains | string | No | No | Domain name. |
| linkAddresses | Array<LinkAddress> | No | No | Network link information. |
| routes | Array<RouteInfo> | No | No | Network route information. |
| dnses | Array<NetAddress> | No | No | Network address. For details, see NetAddress. |
| mtu | number | No | No | Maximum transmission unit (MTU). |
| isIPv4LinkValid24+ | boolean | No | Yes | Whether IPv4 is available on the current network. true: IPv4 is available when the IPv4 address is valid and the default IPv4 route exists. false: IPv4 is unavailable when the IPv4 address is invalid or the default IPv4 route does not exist. Model restriction: This API can be used only in the stage model. |
| isIPv6LinkValid24+ | boolean | No | Yes | Whether IPv6 is available on the current network. true: IPv6 is available when the IPv6 address is valid and the default IPv6 route exists. false: IPv6 is unavailable when the IPv6 address is invalid or the default IPv6 route does not exist. Model restriction: This API can be used only in the stage model. |
RouteInfo
Defines network route information.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| interface | string | No | No | NIC name. |
| destination | LinkAddress | No | No | Destination address. |
| gateway | NetAddress | No | No | Gateway address. |
| hasGateway | boolean | No | No | Whether a gateway is present. Whether a gateway is available. The value true indicates that a gateway is available, and the value false indicates the opposite. |
| isDefaultRoute | boolean | No | No | Whether the route is the default one. Whether the route is the default route. The value true indicates that the route is the default route, and the value false indicates the opposite. Note: The IPv4 default route refers to the route whose destination address is 0.0.0.0/0. The IPv6 default route refers to the route whose destination address is ::/0. |
| isExcludedRoute20+ | boolean | No | Yes | Whether the route is excluded. The value true indicates that the route is excluded, and the value false indicates the opposite. |
LinkAddress
Defines network link information.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| address | NetAddress | No | No | Link address. |
| prefixLength | number | No | No | Length of the link address prefix. |
NetAddress
Defines a network address.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| address | string | No | No | Network address. |
| family | number | No | Yes | Address family identifier. The value is 1 for IPv4 and 2 for IPv6. The default value is 1. |
| port | number | No | Yes | Port number. The value range is [0, 65535]. The default value is 0. |
HttpRequest
type HttpRequest = http.HttpRequest
Defines an HTTP request, which can be created using http.createHttp.
Atomic service API: This API can be used in atomic services since API version 11.
System capability: SystemCapability.Communication.NetStack
| Type | Description |
|---|---|
| http.HttpRequest | HTTP request task. You need to obtain an HTTP request task before calling HttpRequest APIs . |
TCPSocket
type TCPSocket = socket.TCPSocket
Defines a TCPSocket object, which can be created using socket.constructTCPSocketInstance.
System capability: SystemCapability.Communication.NetStack
| Type | Description |
|---|---|
| socket.TCPSocket | TCPSocket object. |
UDPSocket
type UDPSocket = socket.UDPSocket
Defines a UDPSocket object, which can be created using socket.constructUDPSocketInstance.
System capability: SystemCapability.Communication.NetStack
| Type | Description |
|---|---|
| socket.UDPSocket | UDPSocket object. |
NetIpMacInfo22+
Defines information about entries in the IP neighbor table.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| ipAddress | NetAddress | No | No | IP address information. |
| iface | string | No | No | NIC name. |
| macAddress | string | No | No | MAC address. |
ProtocolType23+
Enumerates network protocol types.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Value | Description |
|---|---|---|
| PROTO_TYPE_TCP | 6 | TCP network protocol. |
| PROTO_TYPE_UDP | 17 | UDP network protocol. |
TcpNetPortStatesInfo24+
Describes the TCP port state information.
Model constraint: This API can be used only in the stage model.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| tcpLocalIp | string | No | No | Local IP address of the TCP network. |
| tcpLocalPort | number | No | No | Local port of the TCP network. The value range is [0, 65535]. |
| tcpRemoteIp | string | No | No | Remote IP address of the TCP network. |
| tcpRemotePort | number | No | No | Remote port of the TCP network. The value range is [0, 65535]. |
| tcpUid | number | No | No | UID of the user who listens for the TCP port. |
| tcpPid | number | No | No | PID of the process that listens for the TCP port. |
| tcpState | TcpState | No | No | TCP network status. |
UdpNetPortStatesInfo24+
Describes the UDP port state information.
Model constraint: This API can be used only in the stage model.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| udpLocalIp | string | No | No | Local IP address of the UDP network. |
| udpLocalPort | number | No | No | Local port of the UDP network. The value range is [0, 65535]. |
| udpUid | number | No | No | UID of the user who listens for the UDP port. |
| udpPid | number | No | No | PID of the process that listens for the UDP port. |
NetPortStatesInfo24+
Describes the information about the TCP and UDP ports that are currently listened for by the system.
Model constraint: This API can be used only in the stage model.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| tcpPortStatesInfo | Array<TcpNetPortStatesInfo> | No | Yes | TCP information currently listened for by the system. |
| udpPortStatesInfo | Array<UdpNetPortStatesInfo> | No | Yes | UDP information currently listened for by the system. |
TraceRouteOptions
Defines options for route tracing.
Since: 26.0.0
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| maxJumpNumber | number | No | Yes | Maximum number of jumps. The value range is [1, 30]. The default value is 30. |
| packetsType | PacketsType | No | Yes | Type of the data packet used for probe. The default value is NETCONN_PACKETS_ICMP. |
TraceRouteInfo
Defines the route tracing information.
Since: 26.0.0
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| jumpNo | number | No | No | Jump number. |
| address | string | No | No | IP address to jump to. |
| rtt | number[] | No | No | Round-trip time (RTT), in milliseconds. Five probe packets are sent for each jump. The array elements are the minimum, average, maximum, and standard deviation of the RTTs of these probe packets, respectively. |
ProbeResultInfo
Defines the network probe result information.
Since: 26.0.0
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Communication.NetManager.Core
| Name | Type | Read Only | Optional | Description |
|---|---|---|---|---|
| lossRate | number | No | No | Packet loss rate. The value range is [0, 100]. For example, 100 indicates 100% packet loss, and 50 indicates 50% packet loss. |
| rtt | number[] | No | No | Round-trip time (RTT), in milliseconds. Multiple probe packets are sent to the target host. The number of probe packets is determined by the duration parameter in the queryProbeResult API. The array elements are the minimum, average, maximum, and standard deviation of the RTTs of these probe packets, respectively. |