update interface_bytes and get_bandwidth to support macOS as well

This commit is contained in:
Emma 2024-01-30 13:00:12 -08:00
parent 5f47b1644d
commit 509c2c114f

View file

@ -37,23 +37,38 @@ interface_get() {
echo "$name" echo "$name"
} }
# interface_bytes give interface name and signal tx/rx return Bytes # interface_bytes give an interface name and return both tx/rx Bytes, separated by whitespace (upload first)
interface_bytes() { interface_bytes() {
cat "/sys/class/net/$1/statistics/$2_bytes" case "$(uname -s)" in
Linux)
upload=$(cat "/sys/class/net/$1/statistics/tx_bytes")
download=$(cat "/sys/class/net/$1/statistics/rx_bytes")
echo "$upload $download"
;;
Darwin)
# column 7 is Ibytes (in bytes, rx, download) and column 10 is Obytes (out bytes, tx, upload)
netstat -nbI "$1" | tail -n1 | awk '{print $10 " " $7}'
;;
esac
} }
# get_bandwidth return the number of bytes exchanged for tx and rx # get_bandwidth return the number of bytes exchanged for tx and rx
get_bandwidth() { get_bandwidth() {
upload="$(interface_bytes "$1" "tx")" local upload=0
download="$(interface_bytes "$1" "rx")" local download=0
#wait the interval for Wait for interval to calculate the difference IFS=' ' read -r upload download <<< "$(interface_bytes "$1")"
# wait for interval to calculate the difference
sleep "$INTERVAL" sleep "$INTERVAL"
upload="$(bc <<<"$(interface_bytes "$1" "tx") - $upload")" IFS=' ' read -r new_upload new_download <<< "$(interface_bytes "$1")"
download="$(bc <<<"$(interface_bytes "$1" "rx") - $download")"
#set to 0 by default useful for non-existent interface upload=$(( $new_upload - $upload ))
download=$(( $new_download - $download ))
# set to 0 by default
echo "${upload:-0} ${download:-0}" echo "${upload:-0} ${download:-0}"
} }