USE IPTABLES TO COUNT BANDWIDTH USAGE

One little-known feature of iptables is that, in addition to using it to protect your Linux system from outside menaces, you can also use it to count bandwidth usage. A new logging feature of iptables allows you to log the number of packets that match a particular rule. With this, you can use iptables to count the amount of bandwidth that a system uses. For example, use iptables to add the following two rules:

# iptables -A OUTPUT -p tcp --dport 80 -j LOG

# iptables -A OUTPUT -p tcp --dport 443 -j LOG

This tells iptables to log the number of packets hitting the OUTPUT chain with the TCP protocol destined for ports 80 and 443 (HTTP and HTTPS). To observe the number of packets transferred, you can use:

# iptables -L -v

This displays all of the rules for the available chains. Examining this allows you to look at the OUTPUT chain and specifically at the pkts and bytes columns. This tells you the number of packets and bytes sent to ports 80 and 443 so that you have an idea of how much Web traffic is going out. To get an accurate accounting, you would also use:

# iptables -A INPUT -p tcp --sport 80 -j LOG

# iptables -A INPUT -p tcp --sport 443 -j LOG

This logs all incoming packets from source ports 80 and 443. Now you can add the numbers together to see how many packets and bytes are coming in and going out on the HTTP and HTTPS ports.