Created
February 15, 2018 03:22
-
-
Save tetsu-koba/f298882cc0ded389d11d1f30e7a89726 to your computer and use it in GitHub Desktop.
Show network activity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"log" | |
"os" | |
"strconv" | |
"strings" | |
"time" | |
) | |
const ( | |
rx_bytes = "/statistics/rx_bytes" | |
tx_bytes = "/statistics/tx_bytes" | |
interval = 2 * time.Second | |
) | |
func main() { | |
log.SetFlags(log.Ltime | log.Lshortfile) | |
if len(os.Args) < 2 { | |
fmt.Fprintf(os.Stderr, "Usage: %s eth0\n", os.Args[0]) | |
os.Exit(1) | |
} | |
ifname := os.Args[1] | |
base := "/sys/class/net/" + ifname | |
read := func(f string) uint64 { | |
cnt, err := readCount(f) | |
if err != nil { | |
os.Exit(2) | |
} | |
return cnt | |
} | |
tx0 := read(base + tx_bytes) | |
rx0 := read(base + rx_bytes) | |
ticker := time.NewTicker(interval) | |
defer ticker.Stop() | |
loop: | |
for { | |
select { | |
case t, ok := <-ticker.C: | |
if !ok { | |
break loop | |
} | |
tx := read(base + tx_bytes) | |
rx := read(base + rx_bytes) | |
output(t, tx, rx, tx0, rx0, interval) | |
tx0 = tx | |
rx0 = rx | |
} | |
} | |
} | |
func output(t time.Time, tx, rx, tx0, rx0 uint64, interval time.Duration) { | |
nsec := float64(interval / time.Second) | |
txs := float64(tx-tx0) / nsec / 1024 | |
rxs := float64(rx-rx0) / nsec / 1024 | |
fmt.Printf("t=%d, tx=%d, rx=%d, tx/s=%.1f KB/s, rx/s=%.1f KB/s\n", t.Unix(), tx, rx, txs, rxs) | |
} | |
func readCount(f string) (uint64, error) { | |
b, err := ioutil.ReadFile(f) | |
if err != nil { | |
log.Print(err) | |
return 0, err | |
} | |
cnt, err := strconv.ParseUint(strings.TrimSpace(string(b)), 10, 64) | |
if err != nil { | |
log.Print(err) | |
return 0, err | |
} | |
return cnt, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment