Linux: retrieve per-interface sent/received packet counters (ethernet, ipv4, ipv6)
-
20-08-2019 - |
Question
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.
Solution
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.
OTHER TIPS
On my system, there are files under /sys/class/net/eth0/statistics
, which gives various stats about network interfaces.
This is assuming a vaguely recent Linux which has /sys
(sysfs) mounted.
cat /proc/net/dev
Should contain counters, statistics, and information.
You can always parse the various kernel status files yourself, I think this is what tools like netstat
do.
The man page suggests:
/proc/net/raw
-- RAW socket information/proc/net/tcp
-- TCP socket information/proc/net/udp
-- UDP socket information
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).
The following commands give ipv4/ ipv6 stats maintained system-wide:
netstat --statistics
nstat -z
cat /proc/net/dev_snmp6/eth0 gives ipv6 stats per interface
You can print full ethernet statistics with ethtool:
ethtool -S eth1
You can easily do that in C# in monodevelop:
using System.Net.NetworkInformation;
foreach (NetworkInterface ni in interfaces)
{
// perform your calculations
}