Use iptables to monitor network usage
Iptables is a powerful firewall/packet filtering framework inside Linux, and obviously used for firewalls on desktop, servers, and even embedded Linux devices such as most home internet routers. I was asked to write a script that could monitor and report network usage on one of our machines at work.
I took on the challenge and after searching package repositories and Google for cool Linux console apps that will report network usage, I came came across the idea of using iptables.. seeing as I love iptables, and it is installed by default on most machines it was the perfect solution for us.
The Idea
Iptables can be thought of a bunch of tables each containing some lists of rules called “chains”. There are some default chains which packets must progress through depending on the packets origin and destination. The main and default table that most people use is the ‘filter’ table, the default chains are:
- INPUT – Packets coming to the machine from the network.
- OUTPUT – Packets leaving your machine,
- FORWARD – Packets passing through your machine, if your machine routes packets.
Each of these chains have a default policy, that is what should happen if there is no rules or no rules matching the packet, this is either:
- ACCEPT – Allow the packet into the machine.
- DROP – Drop the packet,
Now the default chains cannot be changed, the packets will work through one of those chains, we can add any rules we want to filter these packets. Netfilter/iptables tracks the amount of data running through chains. So if you want to track all your incoming network usage you can just use the INPUT chain, but if we want to track more specific traffic, we can create a custom chain, add a rule to pass the specific packets to this new chain, and thus monitor the specific traffic! Easy huh!
Before I go into the script and specific iptables configuration I’ll show you readers some useful itptables commands:
- To see the manual page on iptables: man iptables
- To list the rules on the default (filter) table: iptables -L
- To list rules on other tables: iptables -t <tablename> -L
NOTE: If you add a -v you can see packet and byte counts.
Now we move onto what I did.