I am trying to calculate the used bandwidth on the Ethernet interface (which is 1000 Mbit/s). To test my script, I am using the iperf tool to generate huge bandwidths.
The problem I am facing is when eth0_rx1 and eth0_rx2 gets the values which are greater than maximum 32-bit value. I am getting the difference as 0.
Somehow
printf 'eth0 Download rate: %s B/s\n' "$((eth0_rx2-eth0_rx1))"
is giving the correct value, but when tried with
eth0_diff=expr $eth0_rx2 - $eth0_rx1
I am getting the value 0.
Is there a way to handle if rx_bytes or tx_bytes are more than 32 bits?
I am not sure this is an elegant way of calculating used bandwidth. If not, please suggest other alternate way.
Sample output:
eth0_rx1 = 2134947002 \
eth0_rx2= 2159752166 \
eth0 Download rate: 24805164 B/s \
eth0_diff = 12536645 \
eth0_rx_kB = 12242 \
eth0_rx_kB_100 = 1224200 \
eth0_rx_kB_BW = 9
eth0_rx1 = 2159752166 \
eth0_rx2= 2184557522 \
eth0 Download rate: 24805356 B/s \
eth0_diff = 0 \
eth0_rx_kB = 0 \
eth0_rx_kB_100 = 0 \
eth0_rx_kB_BW = 0
Script used:
#!/bin/sh
eth0_rx1=$(cat /sys/class/net/eth0/statistics/rx_bytes)
while sleep 1; do
eth0_rx2=$(cat /sys/class/net/eth0/statistics/rx_bytes)
echo "eth0_rx1 = $eth0_rx1"
echo "eth0_rx2= $eth0_rx2"
printf 'eth0 Download rate: %s B/s\n' "$((eth0_rx2-eth0_rx1))"
eth0_diff=`expr $eth0_rx2 - $eth0_rx1`
echo "eth0_diff = $eth0_diff"
#convert bytes to Kilo Bytes
eth0_rx_kB=`expr $eth0_diff / 1024`
echo "eth0_rx_kB = $eth0_rx_kB"
#bandwidth calculation
eth0_rx_kB=`expr $eth0_rx_kB \* 100`
echo "eth0_rx_kB_100 = $eth0_rx_kB"
#125000 = 1000 Mbit/s
eth0_rx_kB=`expr $eth0_rx_kB / 125000`
echo "eth0_rx_kB_BW = $eth0_rx_kB"
eth0_rx1=$eth0_rx2
eth2_rx1=$eth2_rx2
done
expris not an internal shell part, unlike$(( ...))2) taking your figures myexpr(ubuntu 20.10) give me correct values 3) doesbcgive correct values (e.g.x=$(echo $eth0_rx2 - $eth0_rx1 | bc)) ?/bin/shandexpr? Busybox? If Busybox provides both, I think you should be able to configure it to use 64-bit arithmetic both for the shell andexpr. I peeked at the code and it seems it'd be two different config settings, but didn't double check the actual configuratino./bin/shis likely not Bash? Even if it is Bash, it can behave very differently in POSIX-conformant mode.