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.
Was it helpful?

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

Wireshark (used to be Ethereal) can help you with that.

Netstat Would be my second guess

You can easily do that in C# in monodevelop:

using System.Net.NetworkInformation;

foreach (NetworkInterface ni in interfaces)
{
  // perform your calculations
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top