harmony 鸿蒙@ohos.net.connection (Network Connection Management)

2022-08-09 浏览 (941)

@ohos.net.connection (Network Connection Management)

The network connection management module provides basic network management capabilities. You can obtain the default active data network or the list of all active data networks, enable or disable the airplane mode, and obtain 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.

Modules to Import

import connection from '@ohos.net.connection'

connection.createNetConnection8+

createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection

Creates a NetConnection object. netSpecifier specifies the network, and timeout specifies the timeout duration in ms. timeout is configurable only when netSpecifier is specified. If neither of them is present, the default network is used.

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
netSpecifierNetSpecifierNoNetwork specifier, which specifies the characteristics of a network. If this parameter is not set or is set to undefined, the default network is used.
timeoutnumberNoTimeout duration for obtaining the network specified by netSpecifier. This parameter is valid only when netSpecifier is specified. The default value is 0 if netSpecifier is undefined.

Return value

TypeDescription
NetConnectionHandle of the network specified by netSpecifier.

Example

import connection from '@ohos.net.connection'

// For the default network, you do not need to pass in parameters.
let netConnection = connection.createNetConnection()

// For the cellular network, you need to pass in related network parameters. If the timeout parameter is not specified, the timeout value is 0 by default.
let netConnectionCellular = connection.createNetConnection({
  netCapabilities: {
    bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
  }
})

connection.getDefaultNet8+

getDefaultNet(callback: AsyncCallback<NetHandle>): void

Obtains the default active data network. This API uses an asynchronous callback to return the result. You can use getNetCapabilities to obtain information such as the network type and capabilities.

Required permission: ohos.permission.GET_NETWORK_INFO

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<NetHandle>YesCallback used to return the result. If the default activated data network is obtained successfully, error is undefined and data is the default activated data network. Otherwise, error is an error object.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base'

connection.getDefaultNet((error: BusinessError, data: connection.NetHandle) => {
  console.log(JSON.stringify(error))
  console.log(JSON.stringify(data))
})

connection.getDefaultNet8+

getDefaultNet(): Promise<NetHandle>

Obtains the default active data network. This API uses a promise to return the result. You can use getNetCapabilities to obtain information such as the network type and capabilities.

Required permission: ohos.permission.GET_NETWORK_INFO

System capability: SystemCapability.Communication.NetManager.Core

Return value

TypeDescription
Promise<NetHandle>Promise used to return the result.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
connection.getDefaultNet().then((data: connection.NetHandle) => {
  console.log(JSON.stringify(data))
})

connection.getDefaultNetSync9+

getDefaultNetSync(): NetHandle

Obtains the default active data network in synchronous mode. You can use getNetCapabilities to obtain information such as the network type and capabilities.

Required permission: ohos.permission.GET_NETWORK_INFO

System capability: SystemCapability.Communication.NetManager.Core

Return value

TypeDescription
NetHandleHandle of the default active data network.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'

let netHandle = connection.getDefaultNetSync();

connection.getGlobalHttpProxy10+

getGlobalHttpProxy(callback: AsyncCallback<HttpProxy>): void

Obtains the global HTTP proxy configuration of the network. This API uses an asynchronous callback to return the result.

System API: This is a system API.

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<HttpProxy>YesCallback 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

IDError Message
401Parameter error.
202Non-system applications use system APIs.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base'

connection.getGlobalHttpProxy((error: BusinessError, data: connection.HttpProxy) => {
  console.info(JSON.stringify(error));
  console.info(JSON.stringify(data));
})

connection.getGlobalHttpProxy10+

getGlobalHttpProxy(): Promise<HttpProxy>;

Obtains the global HTTP proxy configuration of the network. This API uses a promise to return the result.

System API: This is a system API.

System capability: SystemCapability.Communication.NetManager.Core

Return value

TypeDescription
Promise<HttpProxy>Promise used to return the result.

Error codes

IDError Message
401Parameter error.
202Non-system applications use system APIs.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base'

connection.getGlobalHttpProxy().then((data: connection.HttpProxy) => {
  console.info(JSON.stringify(data));
}).catch((error: BusinessError) => {
  console.info(JSON.stringify(error));
})

connection.setGlobalHttpProxy10+

setGlobalHttpProxy(httpProxy: HttpProxy, callback: AsyncCallback<void>): void

Sets the global HTTP proxy configuration of the network. This API uses an asynchronous callback to return the result.

System API: This is a system API.

Required permissions: ohos.permission.CONNECTIVITY_INTERNAL

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
httpProxyHttpProxyYesGlobal HTTP proxy configuration of the network.
callbackAsyncCallback<void>YesCallback used to return the result. If the global HTTP proxy configuration of the network is set successfully, error is undefined. Otherwise, error is an error object.

Error codes

IDError Message
201Permission denied.
401Parameter error.
202Non-system applications use system APIs.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base';

let exclusionStr = "192.168,baidu.com"
let exclusionArray = exclusionStr.split(',');
connection.setGlobalHttpProxy({
  host: "192.168.xx.xxx",
  port: 8080,
  exclusionList: exclusionArray
} as connection.HttpProxy).then(() => {
  console.info("success");
}).catch((error: BusinessError) => {
  console.info(JSON.stringify(error));
});

connection.setGlobalHttpProxy10+

setGlobalHttpProxy(httpProxy: HttpProxy): Promise<void>;

Sets the global HTTP proxy configuration of the network. This API uses a promise to return the result.

System API: This is a system API.

Required permissions: ohos.permission.CONNECTIVITY_INTERNAL

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
httpProxyHttpProxyYesGlobal HTTP proxy configuration of the network.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

IDError Message
201Permission denied.
401Parameter error.
202Non-system applications use system APIs.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base';

let exclusionStr = "192.168,baidu.com"
let exclusionArray = exclusionStr.split(',');
connection.setGlobalHttpProxy({
  host: "192.168.xx.xxx",
  port: 8080,
  exclusionList: exclusionArray
} as connection.HttpProxy).then(() => {
  console.info("success");
}).catch((error: BusinessError) => {
  console.info(JSON.stringify(error));
});

connection.getDefaultHttpProxy10+

getDefaultHttpProxy(callback: AsyncCallback<HttpProxy>): void

Obtains the default HTTP proxy configuration of the network. If the global proxy is set, the global HTTP proxy configuration is returned. If setAppNet is used to bind the application to the network specified by NetHandle, the HTTP proxy configuration of this network is returned. In other cases, the HTTP proxy configuration of the default network is returned. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<HttpProxy>YesCallback 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

IDError Message
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base'

connection.getDefaultHttpProxy((error: BusinessError, data: connection.HttpProxy) => {
  console.info(JSON.stringify(error));
  console.info(JSON.stringify(data));
})

connection.getDefaultHttpProxy10+

getDefaultHttpProxy(): Promise<HttpProxy>;

Obtains the default HTTP proxy configuration of the network. If the global proxy is set, the global HTTP proxy configuration is returned. If setAppNet is used to bind the application to the network specified by NetHandle, the HTTP proxy configuration of this network is returned. In other cases, the HTTP proxy configuration of the default network is returned. This API uses a promise to return the result.

System capability: SystemCapability.Communication.NetManager.Core

Return value

TypeDescription
Promise<HttpProxy>Promise used to return the result.

Error codes

IDError Message
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base'

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 information about the network bound to an application. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<NetHandle>YesCallback 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

IDError Message
401Parameter error.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base'

connection.getAppNet((error: BusinessError, data: connection.NetHandle) => {
  console.log(JSON.stringify(error))
  console.log(JSON.stringify(data))
})

connection.getAppNet9+

getAppNet(): Promise<NetHandle>;

Obtains information about the network bound to an application. This API uses a promise to return the result.

System capability: SystemCapability.Communication.NetManager.Core

Return value

TypeDescription
Promise<NetHandle>Promise used to return the result.

Error codes

IDError Message
401Parameter error.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base'

connection.getAppNet().then((data: connection.NetHandle) => {
  console.info(JSON.stringify(data));
}).catch((error: BusinessError) => {
  console.info(JSON.stringify(error));
})

connection.getAppNetSync10+

getAppNetSync(): NetHandle

Obtains information about the network bound to an application. This API returns the result synchronously.

System capability: SystemCapability.Communication.NetManager.Core

Return value

TypeDescription
NetHandleHandle of the data network bound to the application.

Error codes

IDError Message
401Parameter error.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'

let netHandle = connection.getAppNetSync();

connection.SetAppNet9+

setAppNet(netHandle: NetHandle, callback: AsyncCallback<void>): void

Binds an application to the specified network, 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

NameTypeMandatoryDescription
netHandleNetHandleYesHandle of the data network.
callbackAsyncCallback<void>YesCallback used to return the result. If the application is successfully bound to the specified network, error is undefined. Otherwise, error is an error object.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base'

connection.getDefaultNet((error: BusinessError, netHandle: connection.NetHandle) => {
  connection.setAppNet(netHandle, (error: BusinessError, data: void) => {
    console.log(JSON.stringify(error))
    console.log(JSON.stringify(data))
  });
})

connection.SetAppNet9+

setAppNet(netHandle: NetHandle): Promise<void>;

Binds an application to the specified network, so that the application can access the external network only through this network. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
netHandleNetHandleYesHandle of the data network.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base'

connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
  connection.setAppNet(netHandle).then(() => {
    console.log("success")
  }).catch((error: BusinessError) => {
    console.log(JSON.stringify(error))
  })
})

connection.getAllNets8+

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

NameTypeMandatoryDescription
callbackAsyncCallback<Array<NetHandle>>YesCallback 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 data networks. Otherwise, error is an error object.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base'

connection.getAllNets((error: BusinessError, data: connection.NetHandle[]) => {
  console.log(JSON.stringify(error))
  console.log(JSON.stringify(data))
}); 

connection.getAllNets8+

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

TypeDescription
Promise<Array<NetHandle>>Promise used to return the result.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'

connection.getAllNets().then((data: connection.NetHandle[]) => {
  console.log(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

TypeDescription
Array<NetHandle>List of all activated data networks.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'

let netHandle = connection.getAllNetsSync();

connection.getConnectionProperties8+

getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback<ConnectionProperties>): void

Obtains connection properties of the network corresponding to the netHandle. This API uses an asynchronous callback to return the result.

Required permission: ohos.permission.GET_NETWORK_INFO

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
netHandleNetHandleYesHandle of the data network.
callbackAsyncCallback<ConnectionProperties>YesCallback used to return the result. If the connection properties of the network corresponding to the netHandle is obtained successfully, error is undefined and data is the obtained network connection information. Otherwise, error is an error object.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base'

connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
  connection.getConnectionProperties(netHandle, (error: BusinessError, data: connection.ConnectionProperties) => {
    console.log(JSON.stringify(error))
    console.log(JSON.stringify(data))
  })
})

connection.getConnectionProperties8+

getConnectionProperties(netHandle: NetHandle): Promise<ConnectionProperties>

Obtains connection properties of the network corresponding to the netHandle. This API uses a promise to return the result.

Required permission: ohos.permission.GET_NETWORK_INFO

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
netHandleNetHandleYesHandle of the data network.

Return value

TypeDescription
Promise<ConnectionProperties>Promise used to return the result.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'

connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
  connection.getConnectionProperties(netHandle).then((data: connection.ConnectionProperties) => {
    console.log(JSON.stringify(data))
  })
})

connection.getConnectionPropertiesSync10+

getConnectionPropertiesSync(netHandle: NetHandle): ConnectionProperties

Obtains network connection information based on the specified netHandle.

Required permission: ohos.permission.GET_NETWORK_INFO

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
netHandleNetHandleYesHandle of the data network.

Return value

TypeDescription
ConnectionPropertiesNetwork connection information.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'

let netHandle = connection.getDefaultNetSync();
let connectionproperties = connection.getConnectionPropertiesSync(netHandle);

connection.getNetCapabilities8+

getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback<NetCapabilities>): void

Obtains capability information of the network corresponding to the netHandle. This API uses an asynchronous callback to return the result.

Required permission: ohos.permission.GET_NETWORK_INFO

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
netHandleNetHandleYesHandle of the data network.
callbackAsyncCallback<NetCapabilities>YesCallback used to return the result. If the capability information of the network corresponding to the netHandle is obtained successfully, error is undefined and data is the obtained network capability information. Otherwise, error is an error object.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base'

connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
  connection.getNetCapabilities(netHandle, (error: BusinessError, data: connection.NetCapabilities) => {
    console.log(JSON.stringify(error))
    console.log(JSON.stringify(data))
  })
})

connection.getNetCapabilities8+

getNetCapabilities(netHandle: NetHandle): Promise<NetCapabilities>

Obtains capability information of the network corresponding to the netHandle. This API uses a promise to return the result.

Required permission: ohos.permission.GET_NETWORK_INFO

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
netHandleNetHandleYesHandle of the data network.

Return value

TypeDescription
Promise<NetCapabilities>Promise used to return the result.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'

connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
  connection.getNetCapabilities(netHandle).then((data: connection.NetCapabilities) => {
    console.log(JSON.stringify(data))
  })
})

connection.getNetCapabilitiesSync10+

getNetCapabilitiesSync(netHandle: NetHandle): NetCapabilities

Obtains capability information of the network corresponding to the netHandle. This API returns the result synchronously.

Required permission: ohos.permission.GET_NETWORK_INFO

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
netHandleNetHandleYesHandle of the data network.

Return value

TypeDescription
NetCapabilitiesNetwork capability information.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'

let netHandle = connection.getDefaultNetSync();
let getNetCapabilitiesSync = connection.getNetCapabilitiesSync(netHandle);

connection.isDefaultNetMetered9+

isDefaultNetMetered(callback: AsyncCallback<boolean>): void

Checks whether the data traffic usage on the current network is metered. This API uses an asynchronous callback to return the result.

Required permission: ohos.permission.GET_NETWORK_INFO

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<boolean>YesCallback used to return the result. The value true indicates the data traffic usage is metered.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base'

connection.isDefaultNetMetered((error: BusinessError, data: boolean) => {
  console.log(JSON.stringify(error))
  console.log('data: ' + data)
})

connection.isDefaultNetMetered9+

isDefaultNetMetered(): Promise<boolean>

Checks whether the data traffic usage on the current network is metered. This API uses a promise to return the result.

Required permission: ohos.permission.GET_NETWORK_INFO

System capability: SystemCapability.Communication.NetManager.Core

Return value

TypeDescription
Promise<boolean>Promise used to return the result. The value true indicates the data traffic usage is metered.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'

connection.isDefaultNetMetered().then((data: boolean) => {
  console.log('data: ' + data)
})

connection.isDefaultNetMeteredSync10+

isDefaultNetMeteredSync(): boolean

Checks whether the data traffic usage on the current network is metered. This API returns the result synchronously.

Required permission: ohos.permission.GET_NETWORK_INFO

System capability: SystemCapability.Communication.NetManager.Core

Return value

TypeDescription
booleanThe value true indicates the data traffic usage is metered.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'

let isMetered = connection.isDefaultNetMeteredSync();

connection.hasDefaultNet8+

hasDefaultNet(callback: AsyncCallback<boolean>): void

Checks whether the default data network is activated. This API uses an asynchronous callback to return the result. You can use getDefaultNet to obtain the default data network, if any.

Required permission: ohos.permission.GET_NETWORK_INFO

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<boolean>YesCallback used to return the result. The value true indicates the default data network is activated.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base'

connection.hasDefaultNet((error: BusinessError, data: boolean) => {
  console.log(JSON.stringify(error))
  console.log('data: ' + data)
})

connection.hasDefaultNet8+

hasDefaultNet(): Promise<boolean>

Checks whether the default data network is activated. This API uses a promise to return the result. You can use getDefaultNet to obtain the default data network, if any.

Required permission: ohos.permission.GET_NETWORK_INFO

System capability: SystemCapability.Communication.NetManager.Core

Return value

TypeDescription
Promise<boolean>Promise used to return the result. The value true indicates that the default data network is activated.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
connection.hasDefaultNet().then((data: boolean) => {
  console.log('data: ' + data)
})

connection.hasDefaultNetSync10+

hasDefaultNetSync(): boolean

Checks whether the default data network is activated. This API returns the result synchronously.

Required permission: ohos.permission.GET_NETWORK_INFO

System capability: SystemCapability.Communication.NetManager.Core

Return value

TypeDescription
booleanThe value true indicates the default data network is activated.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'

let isDefaultNet = connection.hasDefaultNetSync();

connection.enableAirplaneMode8+

enableAirplaneMode(callback: AsyncCallback<void>): void

Enables the airplane mode. This API uses an asynchronous callback to return the result.

System API: This is a system API.

Required permissions: ohos.permission.CONNECTIVITY_INTERNAL

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result.

Error codes

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

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base'

connection.enableAirplaneMode((error: BusinessError) => {
  console.log(JSON.stringify(error))
})

connection.enableAirplaneMode8+

enableAirplaneMode(): Promise<void>

Enables the airplane mode. This API uses a promise to return the result.

System API: This is a system API.

Required permissions: ohos.permission.CONNECTIVITY_INTERNAL

System capability: SystemCapability.Communication.NetManager.Core

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

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

Example

import connection from '@ohos.net.connection'

connection.enableAirplaneMode().then((error: void) => {
  console.log(JSON.stringify(error))
})

connection.disableAirplaneMode8+

disableAirplaneMode(callback: AsyncCallback<void>): void

Disables the airplane mode. This API uses an asynchronous callback to return the result.

System API: This is a system API.

Required permissions: ohos.permission.CONNECTIVITY_INTERNAL

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result. If the airplane mode is disabled successfully, error is undefined. Otherwise, error is an error object.

Error codes

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

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base'

connection.disableAirplaneMode((error: BusinessError) => {
  console.log(JSON.stringify(error))
})

connection.disableAirplaneMode8+

disableAirplaneMode(): Promise<void>

Disables the airplane mode. This API uses a promise to return the result.

System API: This is a system API.

Required permissions: ohos.permission.CONNECTIVITY_INTERNAL

System capability: SystemCapability.Communication.NetManager.Core

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

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

Example

import connection from '@ohos.net.connection'

connection.disableAirplaneMode().then((error: void) => {
  console.log(JSON.stringify(error))
})

connection.reportNetConnected8+

reportNetConnected(netHandle: NetHandle, callback: AsyncCallback<void>): void

Reports connection of the data network 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

NameTypeMandatoryDescription
netHandleNetHandleYesHandle of the data network. For details, see NetHandle.
callbackAsyncCallback<void>YesCallback used to return the result. If the network status is reported successfully, error is undefined. Otherwise, error is an error object.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from '@ohos.base'

connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
  connection.reportNetConnected(netHandle, (error: BusinessError) => {
    console.log(JSON.stringify(error))
  });
});

connection.reportNetConnected8+

reportNetConnected(netHandle: NetHandle): Promise<void>

Reports connection of the data network 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

NameTypeMandatoryDescription
netHandleNetHandleYesHandle of the data network. For details, see NetHandle.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
  connection.reportNetConnected(netHandle).then(() => {
    console.log(`report success`)
  });
});

connection.reportNetDisconnected8+

reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback<void>): void

Reports disconnection of the data network 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

NameTypeMandatoryDescription
netHandleNetHandleYesHandle of the data network. For details, see NetHandle.
callbackAsyncCallback<void>YesCallback used to return the result. If the network status is reported successfully, error is undefined. Otherwise, error is an error object.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
  connection.reportNetDisconnected(netHandle).then( () => {
    console.log(`report success`)
  });
});

connection.reportNetDisconnected8+

reportNetDisconnected(netHandle: NetHandle): Promise<void>

Reports disconnection of the data network 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

NameTypeMandatoryDescription
netHandleNetHandleYesHandle of the data network. For details, see NetHandle.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
  connection.reportNetDisconnected(netHandle).then( () => {
    console.log(`report success`)
  });
});

connection.getAddressesByName8+

getAddressesByName(host: string, callback: AsyncCallback<Array<NetAddress>>): void

Resolves the host name by using the default network to obtain all IP addresses. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
hoststringYesHost name to resolve.
callbackAsyncCallback<Array<NetAddress>>YesCallback 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

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from "@ohos.base"
connection.getAddressesByName("xxxx", (error: BusinessError, data: connection.NetAddress[]) => {
  console.log(JSON.stringify(error))
  console.log(JSON.stringify(data))
})

connection.getAddressesByName8+

getAddressesByName(host: string): Promise<Array<NetAddress>>

Resolves the host name by using the default network to obtain all IP addresses. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
hoststringYesHost name to resolve.

Return value

TypeDescription
Promise<Array<NetAddress>>Promise used to return the result.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
connection.getAddressesByName("xxxx").then((data: connection.NetAddress[]) => {
  console.log(JSON.stringify(data))
})

NetConnection

Represents the network connection handle.

NOTE When a device changes to the network connected state, the netAvailable, netCapabilitiesChange, and netConnectionPropertiesChange events will be triggered. When a device changes to the network disconnected state, the netLost event will be triggered. When a device switches from a Wi-Fi network to a cellular network, the netLost event will be first triggered to indicate that the Wi-Fi network is lost and then the netAvaliable event will be triggered to indicate that the cellular network is available.

register8+

register(callback: AsyncCallback<void>): void

Registers a listener for network status changes.

Required permission: ohos.permission.GET_NETWORK_INFO

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback 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

IDError Message
201Permission denied.
401Parameter error.
2100002Operation failed. Cannot connect to service.
2100003System internal error.
2101008The same callback exists.
2101022The number of requests exceeded the maximum.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from "@ohos.base"
let netCon: connection.NetConnection = connection.createNetConnection();
netCon.register((error: BusinessError) => {
  console.log(JSON.stringify(error))
})

unregister8+

unregister(callback: AsyncCallback<void>): void

Unregisters the listener for network status changes.

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback 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

IDError Message
201Permission denied.
401Parameter error.
2100002Operation failed. Cannot connect to service.
2100003System internal error.
2101007The callback is not exists.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from "@ohos.base"
let netCon: connection.NetConnection = connection.createNetConnection();
netCon.unregister((error: BusinessError) => {
  console.log(JSON.stringify(error))
})

on('netAvailable')8+

on(type: 'netAvailable', callback: Callback<NetHandle>): void

Registers a listener for netAvailable events.

Model restriction: Before you call this API, make sure that you have called register to add a listener and called unregister API to unsubscribe from status changes of the default network.

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. This field has a fixed value of netAvailable.
netAvailable: event indicating that the data network is available.
callbackCallback<NetHandle>YesCallback used to return the network handle.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from "@ohos.base"

// Create a NetConnection object.
let netCon: connection.NetConnection = connection.createNetConnection();

// Call register to register a listener.
netCon.register((error: BusinessError) => {
  console.log(JSON.stringify(error))
})

// Subscribe to netAvailable events. Event notifications can be received only after register is called.
netCon.on('netAvailable', (data: connection.NetHandle) => {
  console.log(JSON.stringify(data))
})

// Call unregister to unregister the listener.
netCon.unregister((error: BusinessError) => {
  console.log(JSON.stringify(error))
})

on('netBlockStatusChange')8+

on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void

Registers a listener for netBlockStatusChange events. This API uses an asynchronous callback to return the result.

Model restriction: Before you call this API, make sure that you have called register to add a listener and called unregister API to unsubscribe from status changes of the default network.

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. This field has a fixed value of netBlockStatusChange.
netBlockStatusChange: event indicating a change in the network blocking status.
callbackCallback<{ netHandle: NetHandle, blocked: boolean }>YesCallback used to return the network handle (netHandle) and network status (blocked).

Example

import connection from '@ohos.net.connection'
import { BusinessError } from "@ohos.base"

// Create a NetConnection object.
let netCon: connection.NetConnection = connection.createNetConnection();

// Call register to register a listener.
netCon.register((error: BusinessError) => {
  console.log(JSON.stringify(error))
})

// Subscribe to netAvailable events. Event notifications can be received only after register is called.
netCon.on('netAvailable', (data: connection.NetHandle) => {
  console.log(JSON.stringify(data))
})

// Call unregister to unregister the listener.
netCon.unregister((error: BusinessError) => {
  console.log(JSON.stringify(error))
})

on('netCapabilitiesChange')8+

on(type: 'netCapabilitiesChange', callback: Callback<NetCapabilityInfo>): void

Registers a listener for netCapabilitiesChange events.

Model restriction: Before you call this API, make sure that you have called register to add a listener and called unregister API to unsubscribe from status changes of the default network.

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. This field has a fixed value of netCapabilitiesChange.
netCapabilitiesChange: event indicating that the network capabilities have changed.
callbackCallback<NetCapabilityInfo>YesCallback used to return the network handle (netHandle) and capability information (netCap).

Example

import connection from '@ohos.net.connection'
import { BusinessError } from "@ohos.base"

// Create a NetConnection object.
let netCon: connection.NetConnection = connection.createNetConnection();

// Call register to register a listener.
netCon.register((error: BusinessError) => {
  console.log(JSON.stringify(error))
})

// Subscribe to netAvailable events. Event notifications can be received only after register is called.
netCon.on('netAvailable', (data: connection.NetHandle) => {
  console.log(JSON.stringify(data))
})

// Call unregister to unregister the listener.
netCon.unregister((error: BusinessError) => {
  console.log(JSON.stringify(error))
})

on('netConnectionPropertiesChange')8+

on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void

Registers a listener for netConnectionPropertiesChange events.

Model restriction: Before you call this API, make sure that you have called register to add a listener and called unregister API to unsubscribe from status changes of the default network.

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. This field has a fixed value of netConnectionPropertiesChange.
netConnectionPropertiesChange: event indicating that network connection properties have changed.
callbackCallback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>YesCallback used to return the network handle (netHandle) and connection information (connectionProperties).

Example

import connection from '@ohos.net.connection'
import { BusinessError } from "@ohos.base"

// Create a NetConnection object.
let netCon: connection.NetConnection = connection.createNetConnection();

// Call register to register a listener.
netCon.register((error: BusinessError) => {
  console.log(JSON.stringify(error))
})

// Subscribe to netAvailable events. Event notifications can be received only after register is called.
netCon.on('netAvailable', (data: connection.NetHandle) => {
  console.log(JSON.stringify(data))
})

// Call unregister to unregister the listener.
netCon.unregister((error: BusinessError) => {
  console.log(JSON.stringify(error))
})

on('netLost')8+

on(type: 'netLost', callback: Callback<NetHandle>): void

Registers a listener for netLost events.

Model restriction: Before you call this API, make sure that you have called register to add a listener and called unregister API to unsubscribe from status changes of the default network.

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. This field has a fixed value of netLost.
netLost: event indicating that the network is interrupted or normally disconnected.
callbackCallback<NetHandle>YesCallback used to return the network handle (netHandle).

Example

import connection from '@ohos.net.connection'
import { BusinessError } from "@ohos.base"

// Create a NetConnection object.
let netCon: connection.NetConnection = connection.createNetConnection();

// Call register to register a listener.
netCon.register((error: BusinessError) => {
  console.log(JSON.stringify(error))
})

// Subscribe to netAvailable events. Event notifications can be received only after register is called.
netCon.on('netAvailable', (data: connection.NetHandle) => {
  console.log(JSON.stringify(data))
})

// Call unregister to unregister the listener.
netCon.unregister((error: BusinessError) => {
  console.log(JSON.stringify(error))
})

on('netUnavailable')8+

on(type: 'netUnavailable', callback: Callback<void>): void

Registers a listener for netUnavailable events.

Model restriction: Before you call this API, make sure that you have called register to add a listener and called unregister API to unsubscribe from status changes of the default network.

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. This field has a fixed value of netUnavailable.
netUnavailable: event indicating that the network is unavailable.
callbackCallback<void>YesCallback used to return the result, which is empty.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from "@ohos.base"

// Create a NetConnection object.
let netCon: connection.NetConnection = connection.createNetConnection();

// Call register to register a listener.
netCon.register((error: BusinessError) => {
  console.log(JSON.stringify(error))
})

// Subscribe to netAvailable events. Event notifications can be received only after register is called.
netCon.on('netAvailable', (data: connection.NetHandle) => {
  console.log(JSON.stringify(data))
})

// Call unregister to unregister the listener.
netCon.unregister((error: BusinessError) => {
  console.log(JSON.stringify(error))
})

NetHandle8+

Defines the handle of the data network.

Before invoking NetHandle APIs, call getNetHandle to obtain a NetHandle object.

System capability: SystemCapability.Communication.NetManager.Core

Attributes

NameTypeMandatoryDescription
netIdnumberYesNetwork ID. The value 0 indicates no default network. Any other value must be greater than or equal to 100.

bindSocket9+

bindSocket(socketParam: TCPSocket |UDPSocket, callback: AsyncCallback<void>): void

Binds a TCPSocket or UDPSocket object to the data network. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
socketParamTCPSocket |UDPSocketYesTCPSocket or UDPSocket object.
callbackAsyncCallback<void>YesCallback 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

IDError Message
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import socket from "@ohos.net.socket";
import connection from '@ohos.net.connection';
import { BusinessError } from '@ohos.base';

interface Data {
  message: ArrayBuffer,
  remoteInfo: socket.SocketRemoteInfo
}

connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
  let tcp = socket.constructTCPSocketInstance();
  let udp = 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.log('bind fail');
        return;
      }
      netHandle.bindSocket(tcp, (error: BusinessError, data: void) => {
        if (error) {
          console.log(JSON.stringify(error));
        } else {
          console.log(JSON.stringify(data));
        }
      })
    })
  } else {
    let callback: (value: Data) => void = (value: Data) => {
      console.log("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.log('bind fail');
        return;
      }
      udp.on('message', (data: Data) => {
        console.log(JSON.stringify(data))
      });
      netHandle.bindSocket(udp, (error: BusinessError, data: void) => {
        if (error) {
          console.log(JSON.stringify(error));
        } else {
          console.log(JSON.stringify(data));
        }
      })
    })
  }
})

bindSocket9+

bindSocket(socketParam: TCPSocket |UDPSocket): Promise<void>;

Binds a TCPSocket or UDPSocket object to the data network. This API uses a promise to return the result.

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
socketParamTCPSocket |UDPSocketYesTCPSocket or UDPSocket object.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

IDError Message
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import socket from "@ohos.net.socket";
import connection from '@ohos.net.connection';
import { BusinessError } from '@ohos.base';
interface Data {
  message: ArrayBuffer,
  remoteInfo: socket.SocketRemoteInfo
}

connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
  let tcp = socket.constructTCPSocketInstance();
  let udp = 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.log('bind fail');
        return;
      }
      netHandle.bindSocket(tcp, (error: BusinessError, data: void) => {
        if (error) {
          console.log(JSON.stringify(error));
        } else {
          console.log(JSON.stringify(data));
        }
      })
    })
  } else {
    let callback: (value: Data) => void = (value: Data) => {
      console.log("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.log('bind fail');
      return;
    }
    udp.on('message', (data: Data) => {
      console.log(JSON.stringify(data))
    });
    netHandle.bindSocket(udp, (error: BusinessError, data: void) => {
      if (error) {
        console.log(JSON.stringify(error));
      } else {
        console.log(JSON.stringify(data));
      }
    })
  })
}
})

getAddressesByName8+

getAddressesByName(host: string, callback: AsyncCallback<Array<NetAddress>>): void

Resolves the host name by using the corresponding network to obtain all IP addresses. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
hoststringYesHost name to resolve.
callbackAsyncCallback<Array<NetAddress>>YesCallback 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

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from "@ohos.base"

connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
  let host = "xxxx";
  netHandle.getAddressesByName(host, (error: BusinessError, data: connection.NetAddress[]) => {
    console.log(JSON.stringify(error))
    console.log(JSON.stringify(data))
  })
})

getAddressesByName8+

getAddressesByName(host: string): Promise<Array<NetAddress>>

Resolves the host name by using the corresponding network to obtain all IP addresses. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
hoststringYesHost name to resolve.

Return value

TypeDescription
Promise<Array<NetAddress>>Promise used to return the result.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'

connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
  let host = "xxxx";
  netHandle.getAddressesByName(host).then((data: connection.NetAddress[]) => {
    console.log(JSON.stringify(data))
  })
})

getAddressByName8+

getAddressByName(host: string, callback: AsyncCallback<NetAddress>): void

Resolves the host name by using the corresponding network to obtain the first IP address. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
hoststringYesHost name to resolve.
callbackAsyncCallback<NetAddress>YesCallback 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

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'
import { BusinessError } from "@ohos.base"

connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
  let host = "xxxx";
  netHandle.getAddressByName(host, (error: BusinessError, data: connection.NetAddress) => {
    console.log(JSON.stringify(error))
    console.log(JSON.stringify(data))
  })
}) 

getAddressByName8+

getAddressByName(host: string): Promise<NetAddress>

Resolves the host name by using the corresponding network to obtain the first IP address. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.Communication.NetManager.Core

Parameters

NameTypeMandatoryDescription
hoststringYesHost name to resolve.

Return value

TypeDescription
Promise<NetAddress>Promise used to return the result.

Error codes

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.

Example

import connection from '@ohos.net.connection'

connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
  let host = "xxxx";
  netHandle.getAddressByName(host).then((data: connection.NetAddress) => {
    console.log(JSON.stringify(data))
  })
})

NetCap8+

Defines the network capability.

System capability: SystemCapability.Communication.NetManager.Core

NameValueDescription
NET_CAPABILITY_MMS0The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.
NET_CAPABILITY_NOT_METERED11The network traffic is not metered.
NET_CAPABILITY_INTERNET12The network has the Internet access capability, which is set by the network provider.
NET_CAPABILITY_NOT_VPN15The network does not use a virtual private network (VPN).
NET_CAPABILITY_VALIDATED16The Internet access capability of the network is successfully verified by the connection management module.

NetBearType8+

Enumerates network types.

System capability: SystemCapability.Communication.NetManager.Core

NameValueDescription
BEARER_CELLULAR0Cellular network.
BEARER_WIFI1Wi-Fi network.
BEARER_ETHERNET3Ethernet network.

HttpProxy10+

Represents the HTTP proxy configuration.

System capability: SystemCapability.Communication.NetManager.Core

NameTypeMandatoryDescription
hoststringNoHost name of the proxy server.
portnumberNoHost port.
exclusionListArrayNoList 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.

NetSpecifier8+

Provides an instance that bears data network capabilities.

System capability: SystemCapability.Communication.NetManager.Core

NameTypeMandatoryDescription
netCapabilitiesNetCapabilitiesYesNetwork transmission capabilities and bearer types of the data network.
bearerPrivateIdentifierstringNoNetwork identifier. The identifier of a Wi-Fi network is wifi, and that of a cellular network is slot0 (corresponding to SIM card 1).

NetCapabilityInfo10+

Provides an instance that bears data network capabilities.

System capability: SystemCapability.Communication.NetManager.Core

NameTypeMandatoryDescription
netHandleNetHandleYesHandle of the data network.
netCapNetCapabilitiesNoNetwork transmission capabilities and bearer types of the data network.

NetCapabilities8+

Defines the network capability set.

System capability: SystemCapability.Communication.NetManager.Core

NameTypeMandatoryDescription
linkUpBandwidthKbpsnumberNoUplink (device-to-network) bandwidth. The value 0 indicates that the current network bandwidth cannot be evaluated.
linkDownBandwidthKbpsnumberNoDownlink (network-to-device) bandwidth. The value 0 indicates that the current network bandwidth cannot be evaluated.
networkCapArray<NetCap>NoNetwork capability.
bearerTypesArray<NetBearType>YesNetwork type.

ConnectionProperties8+

Defines the network connection properties.

System capability: SystemCapability.Communication.NetManager.Core

NameTypeMandatoryDescription
interfaceNamestringYesNetwork interface card (NIC) name.
domainsstringYesDomain. The default value is "".
linkAddressesArray<LinkAddress>YesLink information.
routesArray<RouteInfo>YesRoute information.
dnsesArray<NetAddress>YesNetwork address. For details, see NetAddress.
mtunumberYesMaximum transmission unit (MTU).

RouteInfo8+

Defines network route information.

System capability: SystemCapability.Communication.NetManager.Core

NameTypeMandatoryDescription
interfacestringYesNIC name.
destinationLinkAddressYesDestination address.
gatewayNetAddressYesGateway address.
hasGatewaybooleanYesWhether a gateway is present.
isDefaultRoutebooleanYesWhether the route is the default route.

LinkAddress8+

Defines network link information.

System capability: SystemCapability.Communication.NetManager.Core

NameTypeMandatoryDescription
addressNetAddressYesLink address.
prefixLengthnumberYesLength of the link address prefix.

NetAddress8+

Defines a network address.

System capability: SystemCapability.Communication.NetManager.Core

NameTypeMandatoryDescription
addressstringYesNetwork address.
familynumberNoAddress family identifier. The value is 1 for IPv4 and 2 for IPv6. The default value is 1.
portnumberNoPort number. The value ranges from 0 to 65535.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙APIs

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

harmony 鸿蒙System Common Events

harmony 鸿蒙API Reference Document Description

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

harmony 鸿蒙BundleStatusCallback

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

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

harmony 鸿蒙@ohos.bundle (Bundle)

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

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