I have two machines with two applications that talk to each other on few network ports (TCP and UDP). I want to count traffic that they send and receive. I need not only overall count but stats per machine per port per day. I tried darkstat, but it doesn't provide stats per day, but only overall counters.

Is there other way that I can count that traffic (I can put some proxy or gateway between that two machines).

5 Answers 5


iptables can give you statistics about how many each rule was triggered, so you can add LOG rules on the ports of interest (lets say port 20 & port 80):

iptables -A INPUT -p tcp --dport 22
iptables -A INPUT -p tcp --dport 80

and then

iptables -n -L -v

will give you number of packets and bytes sent through this ports. Of course you will have to parse from the output the ports that interests you.

If you need exact values, add an -x:

iptables -n -L -v -x

You can add accounting rules to your iptables configuration. These should occur before you accept ESTABLISHED and RELATED traffic or you will miss counting traffic that passes. To count web traffic try a rule like:

iptables -A INPUT -p tcp --dport 80 

If you have a bunch of them you may want to create an accounting chain so you can report and zero counters on it in isolation from other chains.

The Shorewall firewall allows you to easily add accounting rules to your rule set.


Do not forget to include output traffic statistics.

# Port 80 (HTTP).
iptables -A INPUT -p tcp --dport 80
iptables -A OUTPUT -p tcp --sport 80

# Port 443 (HTTPS).
iptables -A INPUT -p tcp --dport 443
iptables -A OUTPUT -p tcp --sport 443

iptables -n -L -v
iptables -n -L -v -x

iptables -n -L -v -x | grep -i "Chain\|:443\|:80"

Chain INPUT (policy DROP 357 packets, 22828 bytes)
 1286265 75076978 ACCEPT tcp  --  *      *  tcp dpt:80
 1305378 75018232 ACCEPT tcp  --  *      *  tcp dpt:443

Chain OUTPUT (policy ACCEPT 303516 packets, 94716311 bytes)
     442   255112        tcp  --  *      *  tcp spt:80
      46    10515        tcp  --  *      *  tcp spt:443

Utilize the tcpdump,

tcpdump -i any -nnn

the outputs of the above command would include the timestamp, src/dest ip addresses, port and the packet length. With those information, you can achieve your goal easily by a well written script.


It's not clear whether you need usage per destination IP, but vnstat is a useful tool for recording traffic usage per interface. Install it and then run vnstat -u -i eth0 for each interface you want to monitor. To then get the usage per day use vnstat -i eth0 -d.

  • 1
    I don't think that using vnstat I can get stat per port... Or am I wrong?
    – pbm
    Jun 29, 2012 at 19:27
  • 2
    @pbm Ah, you mean TCP/UDP port. No, vnstat won't do that.
    – mgorven
    Jun 29, 2012 at 20:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .