iptables is a user space utilities which uses Netfilter framework in the Linux kernel. It groups network packet processing rules into tables by function, each of them have chains of processing rules.

The linux kernel automatically tracks packet and byte counts for iptables each rule, This information can be used too do accounting on network usage.

The network usage is counted by packet and bytes only, no number of connections etc..

#iptables -nvxL
Chain INPUT (policy DROP 38545 packets, 5435287 bytes)
pkts      bytes target  prot opt in     out     source         destination        
  44       2960 ACCEPT  tcp  --  *      *        tcp
Chain OUTPUT (policy ACCEPT 143450 packets, 46125613 bytes)
pkts      bytes target  prot opt in     out     source         destination         
  30      22040 ACCEPT  tcp  --  *      *      tcp

In example above

  • -L lists all the rules.
  • -n does not resolve the ip addresses.
  • -v lists the packet and byte count.
  • -x displays the byte count (otherwise it gets abbreviated to 200K, 3M, etc).

However, in iptables state matching, there is a state called 'NEW', can be used for accounting rule to count a port(or ports, depends on rule ) connection attempts.

Here is the 'NEW' definition in iptables connection state, it says:

The NEW state tells us that the packet is the first packet that we see. 
This means that the first packet that the conntrack module sees, within a specific connection, will be matched.
For example, if we see a SYN packet and it is the first packet in a connection that we see, it will match.
However, the packet may as well not be a SYN packet and still be considered NEW.
This may lead to certain problems in some instances, but it may also be extremely helpful when we need to pick up
lost connections from other firewalls, or when a connection has already timed out, but in reality is not closed.

So, If use 'NEW' state matching, only the first packet is counted for each connection(including attempts)

Here is one example:

## Port Accounting rules
-A INPUT -m state --state NEW -m tcp -p tcp --dport 8080 -j port_8080
-A port_8080 -m state --state NEW -m tcp -p tcp --dport 8080 -j Accept

Note: in the example above, the iptables rule has a 'NEW' state matching, thus, only the first packet is counted for each connection, or attempt. It also can be used as number of connections(or attempt) to a particular port.

Check the port 8080 connection attempts

iptables -nxvL Port_8080

Reset the port 8080 connection counter

iptables -Z Port_8080

Note: There is exceptional case that the port counting could be wrong, that is when long idling connection is timed out in iptables conntrack table, the next packet will e counted as 'NEW', as described in 'NEW' state explaination.

Comments powered by CComment