Counters

From nftables wiki
Revision as of 14:42, 2 April 2021 by Fmyhr (talk | contribs) (Added sections on listing and resetting named counters.)
Jump to navigation Jump to search

With nftables you need to explicitly specify a counter for each rule you want to count.

Anonymous counters

An anonymous counter is local to the single rule in which it appears. The following example uses an anonymous counter to count all tcp traffic routed to the local host:

table ip counter_demo {
    chain IN {
        type filter hook input priority filter; policy drop;

        protocol tcp counter
    }
}

Note that the position of the counter statement within your rule is significant, because nftables evaluates expressions and statements linearly from left to right. If the above rule were written instead:

        counter protocol tcp

then every packet routed to your host (not just tcp packets) will update the counter!


Named counters

Declaring and using named counters

You can also declare named counters, which can be used in multiple rules, e.g.:

table inet named_counter_demo {

    counter cnt_http {
    }

    counter cnt_smtp {
    }

    chain IN {
        type filter hook input priority filter; policy drop;

        tcp dport   25 counter name cnt_smtp
        tcp dport   80 counter name cnt_http
        tcp dport  443 counter name cnt_http
   }
}

The above example defines two counters named cnt_http and cnt_smtp and uses them in rules to count http(s) and smtp packets routed to the local host. (This example is contrived to show using a single named counter in multiple rules; the two rules using cnt_http can easily be combined by using an anonymous set.)


Listing named counters

  • List a particular counter:
% nft list counter named_counter_demo cnt_http
  • List all counters in a particular table:
% nft list counters table inet named_counter_demo
  • List all counters in ruleset:
% nft list counters


Resetting named counters

  • Reset a particular counter:
% nft reset counter named_counter_demo cnt_http
  • Reset all counters in a particular table:
% nft reset counters table inet named_counter_demo
  • Reset all counters in ruleset:
% nft reset counters