How should I determine the current network utilization?
I think ifstat will help you :
[root@localhost ~]# ifstat -i eth0 -q 1 1 eth0 KB/s in KB/s out 3390.26 69.69
The best way to do it simply is probably to parse /proc/net/dev
(be warned that /proc
is not portable). Here's a bash
script I quickly put together that should be able to calculate it:
#!/bin/bash
_die() {
printf '%s\n' "$@"
exit 1
}
_interface=$1
[[ ${_interface} ]] || _die 'Usage: ifspeed [interface]'
grep -q "^ *${_interface}:" /proc/net/dev || _die "Interface ${_interface} not found in /proc/net/dev"
_interface_bytes_in_old=$(awk "/^ *${_interface}:/"' { if ($1 ~ /.*:[0-9][0-9]*/) { sub(/^.*:/, "") ; print $1 } else { print $2 } }' /proc/net/dev)
_interface_bytes_out_old=$(awk "/^ *${_interface}:/"' { if ($1 ~ /.*:[0-9][0-9]*/) { print $9 } else { print $10 } }' /proc/net/dev)
while sleep 1; do
_interface_bytes_in_new=$(awk "/^ *${_interface}:/"' { if ($1 ~ /.*:[0-9][0-9]*/) { sub(/^.*:/, "") ; print $1 } else { print $2 } }' /proc/net/dev)
_interface_bytes_out_new=$(awk "/^ *${_interface}:/"' { if ($1 ~ /.*:[0-9][0-9]*/) { print $9 } else { print $10 } }' /proc/net/dev)
printf '%s: %s\n' 'Bytes in/sec' "$(( _interface_bytes_in_new - _interface_bytes_in_old ))" \
'Bytes out/sec' "$(( _interface_bytes_out_new - _interface_bytes_out_old ))"
# printf '%s: %s\n' 'Kilobytes in/sec' "$(( ( _interface_bytes_in_new - _interface_bytes_in_old ) / 1024 ))" \
# 'Kilobytes out/sec' "$(( ( _interface_bytes_out_new - _interface_bytes_out_old ) / 1024 ))"
# printf '%s: %s\n' 'Megabits in/sec' "$(( ( _interface_bytes_in_new - _interface_bytes_in_old ) / 131072 ))" \
# 'Megabits out/sec' "$(( ( _interface_bytes_out_new - _interface_bytes_out_old ) / 131072 ))"
_interface_bytes_in_old=${_interface_bytes_in_new}
_interface_bytes_out_old=${_interface_bytes_out_new}
done
Bear in mind that sleep
does not consider the amount of time it takes to do the operations in the while loop, so this is (very slightly) inaccurate. On my 600mhz coppermine, the loop takes 0.011 seconds -- a negligible inaccuracy for most purposes. Bear in mind also when using the (commented out) kilobyte/megabit outputs, bash only understands integer arithmetic.
There are network traffic monitors like vnstat that keeps monthly records of your traffic, or slurm which takes it's values directly from those stored in kernel. It's available in most distro repos.
Here is what I see when I run slurm -i ra0
: