views:

1586

answers:

7

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.
A: 

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

Netstat Would be my second guess

dsm
Thanks, but I'm looking for a way to retrieve these counters on a "standard" linux system without installing any additional software.
Cayle Spandon
Netstat should come pre-installed in most *nixes
dsm
+2  A: 

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.

xahtep
Sounds promising. Can you elaborate and/or point to a book/website describing this? Also, would there be a performance implication if I want this turned on "all the time" on a production system?
Cayle Spandon
I updated the answer to have an example, hope this helps. There won't be any noticeable performance hit for this as it just updates a few in-memory counters as the packets flow through.
xahtep
Great! This is what I needed. Thanks!
Cayle Spandon
+1  A: 

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.

unwind
The only relevant kernel status file which I could find was /proc/dev/net. It reports RX-OK and TX-OK per interface. I suspect these are ethernet frame counters. How would I get IPv4 and IPv6 packet counters?Note that I'm looking for itnerface stats, not for connection (socket) stats.
Cayle Spandon
A: 

Either just parse the output of netstat -i. Or strace netstat -i, and use that to work out where it looks for the information.

Douglas Leeder
netstat reports RX-OK and TX-OK per interface. I suspect these are ethernet frame counters. How would I get IPv4 and IPv6 packet counters?
Cayle Spandon
A: 

ifconfig tells you the amount of data transferred (bytes and packets).

Aaron Digulla
ifconfig reports RX packets and TX packet per interface. I suspect these are ethernet frame counters. How would I get IPv4 and IPv6 packet counters?
Cayle Spandon
No idea :/ I don't have an IPv6 system so I can't tell what ifconfig prints there :(
Aaron Digulla
+2  A: 

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

MarkR
A: 

cat /proc/net/dev