openharmony 鸿蒙 js-apis-net-netfirewall

2025-06-12 浏览 (1)

@ohos.net.netFirewall (Network Firewall)

The netFirewall module implements the firewall query functionality. It allows applications to query the firewall interception records of the device.

NOTE

The initial APIs of this module are supported since API version 15. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Modules to Import

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

netFirewall.getNetFirewallPolicy

getNetFirewallPolicy(userId: number): Promise<NetFirewallPolicy>

Obtains a firewall policy.

Required permission: ohos.permission.GET_NET_FIREWALL

System capability: SystemCapability.Communication.NetManager.NetFirewall

Parameters

NameTypeMandatoryDescription
userIdnumberYesExisting user ID.

Return value

TypeDescription
Promise<NetFirewallPolicy>Promise used to return the result, which is a firewall policy.

Error codes

For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.
29400000The specified user does not exist.

Example

import { netFirewall } '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

netFirewall.getNetFirewallPolicy(100).then((result: netFirewall.NetFirewallPolicy) => {
  console.info('firewall policy: ', JSON.stringify(result));
}, (reason: BusinessError) => {
  console.error('get firewall policy failed: ', JSON.stringify(reason));
});

netFirewall.updateNetFirewallRule

updateNetFirewallRule(rule: NetFirewallRule): Promise<void>

Updates a firewall rule.

Required permission: ohos.permission.MANAGE_NET_FIREWALL

System capability: SystemCapability.Communication.NetManager.NetFirewall

Parameters

NameTypeMandatoryDescription
ruleNetFirewallRuleYesFirewall rule.

Return value

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

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.
29400000The specified user does not exist.
29400002The number of IP address rules in the firewall rule exceeds the maximum.
29400003The number of port rules in the firewall rule exceeds the maximum.
29400004The number of domain rules in the firewall rule exceeds the maximum.
29400005The number of domain rules exceeds the maximum.
29400006The specified rule does not exist.
29400007The dns rule is duplication.

Example

import { netFirewall } '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

let ipRuleUpd: netFirewall.NetFirewallRule = {
  id: 1,
  name: "rule1",
  description: "rule1 description update",
  direction: netFirewall.NetFirewallRuleDirection.RULE_IN,
  action:netFirewall.NetFirewallRuleDirection.RULE_DENY,
  type: netFirewall.NetFirewallRuleType.RULE_IP,
  isEnabled: false,
  appUid: 20001,
  localIps: [
    {
      family: 1,
      type: 1,
      address: "10.10.1.1",
      mask: 24
    },{
      family: 1,
      type: 2,
      startIp: "10.20.1.1",
      endIp: "10.20.1.10"
    }],
  userId: 100
};
netFirewall.updateNetFirewallRule(ipRuleUpd).then(() => {
  console.info('update firewall rule success.');
}, (reason: BusinessError) => {
  console.error('update firewall rule failed: ', JSON.stringify(reason));
});

netFirewall.removeNetFirewallRule

removeNetFirewallRule(userId: number, ruleId: number): Promise<void>

Removes a firewall rule.

Required permission: ohos.permission.MANAGE_NET_FIREWALL

System capability: SystemCapability.Communication.NetManager.NetFirewall

Parameters

NameTypeMandatoryDescription
ruleNetFirewallRuleYesFirewall rule.
userIdnumberYesExisting user ID.
ruleIdnumberYesID of the firewall rule.

Return value

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

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.
29400000The specified user does not exist.
29400006The specified rule does not exist.

Example

import { netFirewall } '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

netFirewall.removeNetFirewallRule(100, 1).then(() => {
  console.info("delete firewall rule success.");
}).catch((error : BusinessError) => {
  console.error("delete firewall rule failed: " + JSON.stringify(error));
});

netFirewall.getNetFirewallRules

getNetFirewallRules(userId: number, requestParam: RequestParam): Promise<FirewallRulePage>

Obtains firewall rules by user ID. You need to specify the pagination query parameter when calling this API.

Required permission: ohos.permission.GET_NET_FIREWALL

System capability: SystemCapability.Communication.NetManager.NetFirewall

Parameters

NameTypeMandatoryDescription
userIdnumberYesExisting user ID.
requestParamRequestParamYesPagination query parameter.

Return value

TypeDescription
Promise<FirewallRulePage>Promise used to return the result, which is list of firewall rules.

Error codes

For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.
29400000The specified user does not exist.

Example

import { netFirewall } '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

let ruleParam: netFirewall.RequestParam = {
  page: 1,
  pageSize: 10,
  orderField: netFirewall.NetFirewallOrderField.ORDER_BY_RULE_NAME,
  orderType: netFirewall.NetFirewallOrderType.ORDER_ASC
};
netFirewall.getNetFirewallRules(100, ruleParam).then((result: netfirewall.FirewallRulePage) => {
  console.info("result:", JSON.stringify(result));
}, (error: BusinessError) => {
  console.error("get firewall rules failed: " + JSON.stringify(error));
});

netFirewall.getNetFirewallRule

getNetFirewallRule(userId: number, ruleId: number): Promise<NetFirewallRule>

Obtains a firewall rule based on the specified user ID and rule ID.

Required permission: ohos.permission.GET_NET_FIREWALL

System capability: SystemCapability.Communication.NetManager.NetFirewall

Parameters

NameTypeMandatoryDescription
userIdnumberYesExisting user ID.
ruleIdnumberYesID of the firewall rule.

Return value

TypeDescription
Promise<NetFirewallRule>Promise used to return the result, which is a firewall rule.

Error codes

For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.
29400000The specified user does not exist.
29400006The specified rule does not exist.

Example

import { netFirewall } '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

netFirewall.getNetFirewallRule(100, 1).then((rule: netFirewall.NetFirewallRule) => {
  console.info("result:", JSON.stringify(rule));
}).catch((error : BusinessError) => {
  console.error(" get firewall rules failed: " + JSON.stringify(error));
});

netFirewall.setNetFirewallPolicy

setNetFirewallPolicy(userId: number, policy: NetFirewallPolicy): Promise<void>

Sets a firewall policy.

Required permission: ohos.permission.MANAGE_NET_FIREWALL

System capability: SystemCapability.Communication.NetManager.NetFirewall

Parameters

NameTypeMandatoryDescription
userIdnumberYesExisting user ID.
policyNetFirewallPolicyYesFirewall policy.

Return value

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

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.
29400000The specified user does not exist.

Example

import { netFirewall } '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

let policy: netFirewall.NetFirewallPolicy = {
  isOpen: true,
  inAction: netFirewall.FirewallRuleAction.RULE_DENY,
  outAction: netFirewall.FirewallRuleAction.RULE_ALLOW
};
netFirewall.setNetFirewallPolicy(100, policy).then(() => {
  console.info("set firewall policy success.");
}).catch((error : BusinessError) => {
  console.error("set firewall policy failed: " + JSON.stringify(error));
});

netFirewall.addNetFirewallRule

addNetFirewallRule(rule: NetFirewallRule): Promise<number>

Adds a firewall rule.

Required permission: ohos.permission.MANAGE_NET_FIREWALL

System capability: SystemCapability.Communication.NetManager.NetFirewall

Parameters

NameTypeMandatoryDescription
ruleNetFirewallRuleYesFirewall rule.

Return value

TypeDescription
Promise<number>Promise used to return the result, which is the firewall rule ID automatically generated by the system.

Error codes

For details about the error codes, see Network Connection Management Error Codes and Universal Error Codes.

IDError Message
201Permission denied.
401Parameter error.
2100001Invalid parameter value.
2100002Operation failed. Cannot connect to service.
2100003System internal error.
29400000The specified user does not exist.
29400001The number of firewall rules exceeds the maximum.
29400002The number of IP address rules in the firewall rule exceeds the maximum.
29400003The number of port rules in the firewall rule exceeds the maximum.
29400004The number of domain rules in the firewall rule exceeds the maximum.
29400005The number of domain rules exceeds the maximum.
29400007The dns rule is duplication.

Example

import { netFirewall } '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

let ipRule: netFirewall.NetFirewallRule = {
  name: "rule1",
  description: "rule1 description",
  direction: netFirewall.NetFirewallRuleDirection.RULE_IN,
  action:netFirewall.NetFirewallRuleDirection.RULE_DENY,
  type: netFirewall.NetFirewallRuleType.RULE_IP,
  isEnabled: true,
  appUid: 20001,
  localIps: [
    {
      family: 1,
      type: 1,
      address: "10.10.1.1",
      mask: 24
    },{
      family: 1,
      type: 2,
      startIp: "10.20.1.1",
      endIp: "10.20.1.10"
    }],
  remoteIps:[
    {
      family: 1,
      type: 1,
      address: "20.10.1.1",
      mask: 24
    },{
      family: 1,
      type: 2,
      startIp: "20.20.1.1",
      endIp: "20.20.1.10"
    }],
  protocol: 6,
  localPorts: [
    {
      startPort: 1000,
      endPort: 1000
    },{
      startPort: 2000,
      endPort: 2001
    }],
  remotePorts: [
    {
      startPort: 443,
      endPort: 443
    }],
  userId: 100
};
netFirewall.addNetFirewallRule(ipRule).then((result: number) => {
  console.info('rule Id: ', result);
}, (reason: BusinessError) => {
  console.error('add firewall rule failed: ', JSON.stringify(reason));
});

let domainRule: netFirewall.NetFirewallRule = {
  name: "rule2",
  description: "rule2 description",
  direction: netFirewall.NetFirewallRuleDirection.RULE_IN,
  action:netFirewall.NetFirewallRuleDirection.RULE_DENY,
  type: netFirewall.NetFirewallRuleType.RULE_DOMAIN,
  isEnabled: true,
  appUid: 20002,
  domains: [
    {
      isWildcard: false,
      domain: "www.example.cn"
    },{
      isWildcard: true,
      domain: "*.example.cn"
    }],
  userId: 100
};
netFirewall.addNetFirewallRule(domainRule).then((result: number) => {
  console.info('rule Id: ', result);
}, (reason: BusinessError) => {
  console.error('add firewall rule failed: ', JSON.stringify(reason));
});

let dnsRule: netFirewall.NetFirewallRule = {
  name: "rule3",
  description: "rule3 description",
  direction: netFirewall.NetFirewallRuleDirection.RULE_IN,
  action:netFirewall.NetFirewallRuleDirection.RULE_DENY,
  type: netFirewall.NetFirewallRuleType.RULE_DNS,
  isEnabled: true,
  appUid: 20003,
  primaryDns: "4.4.4.4",
  standbyDns: "8.8.8.8",
  userId: 100
};
netFirewall.addNetFirewallRule(dnsRule).then((result: number) => {
  console.info('rule Id: ', result);
}, (reason: BusinessError) => {
  console.error('add firewall rule failed: ', JSON.stringify(reason));
});

NetFirewallRule

Defines a firewall rule.

System capability: SystemCapability.Communication.NetManager.NetFirewall

NameTypeMandatoryDescription
userIdnumberYesExisting user ID.
namestringYesRule name. This parameter is mandatory and can contain a maximum of 128 characters.
directionNetFirewallRuleDirectionYesInterception direction, which can be inbound or outbound.
actionFirewallRuleActionYesAction.
typeNetFirewallRuleTypeYesRule type.
isEnabledbooleanYesWhether to enable the firewall rule. The value true means to enable the firewall rule, and the value false means the opposite.
idnumberNoFirewall rule ID.
descriptionstringNoFirewall rule description. This parameter is optional and can contain a maximum of 256 characters.
appUidnumberNoApplication or service UID.
localIpsArray<NetFirewallIpParams>NoList of local IP addresses. This parameter is valid when ruleType is set to RULE_IP. A maximum of 10 local IP addresses are supported.
remoteIpsArray<NetFirewallIpParams>NoList of remote IP addresses. This parameter is valid when ruleType is set to RULE_IP. A maximum of 10 local IP addresses are supported.
protocolnumberNoProtocol. The value 6 indicates TCP and value 17 indicates UDP. This parameter is valid only when ruleType is set to RULE_IP.
localPortsArray<NetFirewallPortParams>NoList of local ports. This parameter is valid when ruleType is set to RULE_IP. A maximum of 10 local ports are supported.
remotePortsArray<NetFirewallPortParams>NoList of remote ports. This parameter is valid when ruleType is set to RULE_IP. A maximum of 10 remote ports are supported.
domainsArray<NetFirewallDomainParams>NoList of domain names. This parameter is valid only when ruleType is set to RULE_DOMAIN.
dnsNetFirewallDnsParamsNoList of DNS server names. This parameter is valid only when ruleType is set to RULE_DNS.

RequestParam

Defines query parameters.

System capability: SystemCapability.Communication.NetManager.NetFirewall

NameTypeMandatoryDescription
pagenumberYesPage number. The value range is [1,1000].
pageSizenumberYesPage size. The value range is [1,50].
orderFieldNetFirewallOrderFieldYesSorting order field.
orderTypeNetFirewallOrderTypeYesSorting order type.

FirewallRulePage

Defines the pagination structure for firewall rules.

System capability: SystemCapability.Communication.NetManager.NetFirewall

NameTypeMandatoryDescription
pagenumberYesCurrent page number. The value range is [1,1000].
pageSizenumberYesPage size. The value range is [1,50].
totalPagenumberYesTotal number of pages. The value range is [1,1000].
dataArray<NetFirewallRule>YesPage data.

NetFirewallPolicy

Defines a firewall policy.

System capability: SystemCapability.Communication.NetManager.NetFirewall

NameTypeMandatoryDescription
isOpenbooleanYesWhether to enable or disable the firewall. The value true means to enable the firewall, and the value false means the opposite.
inActionFirewallRuleActionYesInbound action.
outActionFirewallRuleActionYesOutbound action.

NetFirewallRuleDirection

Enumerates interception directions for firewall rules.

System capability: SystemCapability.Communication.NetManager.NetFirewall

NameValueDescription
RULE_IN1Inbound direction.
RULE_OUT2Outbound direction.

FirewallRuleAction

Enumerates actions for firewall rules.

System capability: SystemCapability.Communication.NetManager.NetFirewall

NameValueDescription
RULE_ALLOW0Allowing network connection.
RULE_DENY1Denying network connection.

NetFirewallRuleType

Enumerates firewall rule types.

System capability: SystemCapability.Communication.NetManager.NetFirewall

NameValueDescription
RULE_IP1IP address-based firewall rule.
RULE_DOMAIN2Domain name-based rule.
RULE_DNS3DNS-based firewall rule.

NetFirewallOrderField

Enumerates firewall rule sorting types.

System capability: SystemCapability.Communication.NetManager.NetFirewall

NameValueDescription
ORDER_BY_RULE_NAME1Sorting of firewall rules by name.
ORDER_BY_RECORD_TIME100Sorting of firewall rules by time.

NetFirewallOrderType

Enumerates firewall rule sorting orders.

System capability: SystemCapability.Communication.NetManager.NetFirewall

NameValueDescription
ORDER_ASC1Sorting in ascending order.
ORDER_DESC100Sorting in descending order.

NetFirewallIpParams

System capability: SystemCapability.Communication.NetManager.NetFirewall

NameTypeMandatoryDescription
typenumberYesIP address type. The value 1 indicates an IP address or subnet. When a single IP address is used, the mask is 32. The value 2 indicates an IP address segment.
familynumberNoIP address family. The value 1 indicates IPv4 and value 2 indicates IPv6. The default value is IPv4. Other values are not supported.
addressstringNoIP address. This parameter is valid only when type is set to 1.
masknumberNoSubnet mask for an IPv4 address and prefix for an IPv6 address. This parameter is valid only when type is set to 1.
startIpstringNoStart IP address: This parameter is valid only when type is set to 2.
endIpstringNoEnd IP address: This parameter is valid only when type is set to 2.

NetFirewallPortParams

Defines the port parameters of a firewall rule.

System capability: SystemCapability.Communication.NetManager.NetFirewall

NameTypeMandatoryDescription
startPortnumberYesStart port number.
endPortnumberYesEnd port number.

NetFirewallDomainParams

Defines the domain information of a firewall rule.

System capability: SystemCapability.Communication.NetManager.NetFirewall

NameTypeMandatoryDescription
isWildcardbooleanYesWhether to contain wildcards. The value true means to contain wildcards, and the value false means the opposite.
domainstringYesDNS domain. If isWildcard is false, you need to specify the complete domain name.

NetFirewallDnsParams

Defines the DNS information of a firewall rule.

System capability: SystemCapability.Communication.NetManager.NetFirewall

NameTypeMandatoryDescription
primaryDnsstringYesActive DNS server.
standbyDnsstringNoStandby DNS server.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Network Kit

harmony 鸿蒙NetConn_ConnectionProperties

harmony 鸿蒙NetConn_HttpProxy

harmony 鸿蒙NetConn_NetAddr

harmony 鸿蒙NetConn_NetCapabilities

harmony 鸿蒙NetConn_NetConnCallback

harmony 鸿蒙NetConn_NetHandle

harmony 鸿蒙NetConn_NetHandleList

harmony 鸿蒙NetConn_NetSpecifier

harmony 鸿蒙NetConn_Route

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