On Linux, how can I (programmatically) retrieve the following counters on a per-interface basis:
- Sent/received ethernet frames,
- Sent/received IPv4 packets,
- Sent/received IPv6 packets.
On Linux, how can I (programmatically) retrieve the following counters on a per-interface basis:
You should be able to do this using iptables
rules and packet counters, e.g.
# input and output must be accounted for separately
# ipv4, eth0
iptables -I INPUT -i eth0
iptables -I OUTPUT -o eth0
# ipv6, eth0
ip6tables -I INPUT -i eth0
ip6tables -I OUTPUT -o eth0
And to view the stats, parse the output of these:
iptables -L -vxn
ip6tables -L -vxn
You should also look up the -Z
flag for when you want to reset the counters.
You can always parse the various kernel status files yourself, I think this is what tools like netstat do. The man page suggests:
I guess there should be a non-proc way to do this, perhaps in /sys too? I had a quick look but didn't find anything.
Either just parse the output of netstat -i
. Or strace netstat -i
, and use that to work out where it looks for the information.
ifconfig
tells you the amount of data transferred (bytes and packets).
On my system, there are files under /sys/class/net/eth0/statistics which give various stats about network interfaces.
This is assuming a vaguely recent Linux which has /sys mounted