LoginSignup
4
10

More than 5 years have passed since last update.

Linuxでネットワークインタフェースの活動状況を調べる by Golang

Last updated at Posted at 2018-02-15

/sys/class/net/eth0/statistics/

/sys/class/net/eth0/statistics/には各種のネットワークのカウンタがあります。

$ ls /sys/class/net/eth0/statistics/
collisions     rx_errors         rx_packets         tx_errors
multicast      rx_fifo_errors    tx_aborted_errors  tx_fifo_errors
rx_bytes       rx_frame_errors   tx_bytes           tx_heartbeat_errors
rx_compressed  rx_length_errors  tx_carrier_errors  tx_packets
rx_crc_errors  rx_missed_errors  tx_compressed      tx_window_errors
rx_dropped     rx_over_errors    tx_dropped

送信、受信の累計のバイト数もわかります。

$ cat /sys/class/net/eth0/statistics/rx_bytes 
42799020
$ cat /sys/class/net/eth0/statistics/tx_bytes 
732878

これを利用して、ネットワークインタフェースの活動状況をダンプするプログラムをgolangで書きました。

Golangのサンプルプログラム

gistに貼りました。
https://gist.github.com/tetsu-koba/f298882cc0ded389d11d1f30e7a89726

$ go build
$ ./net_activity 
Usage: ./net_activity eth0

ネットワークインタフェース名を引数に指定して実行します。

$ ./net_activity eth0
t=1518663877, tx=12391555, rx=530245513, tx/s=0.0 KB/s, rx/s=1.9 KB/s
t=1518663879, tx=12391633, rx=530247972, tx/s=0.0 KB/s, rx/s=1.2 KB/s
t=1518663881, tx=12392447, rx=530254973, tx/s=0.4 KB/s, rx/s=3.4 KB/s
t=1518663883, tx=12392533, rx=530258811, tx/s=0.0 KB/s, rx/s=1.9 KB/s
t=1518663885, tx=12393015, rx=530261346, tx/s=0.2 KB/s, rx/s=1.2 KB/s
t=1518663887, tx=12393101, rx=530263002, tx/s=0.0 KB/s, rx/s=0.8 KB/s
t=1518663889, tx=12393101, rx=530267283, tx/s=0.0 KB/s, rx/s=2.1 KB/s
t=1518663891, tx=12393179, rx=530269833, tx/s=0.0 KB/s, rx/s=1.2 KB/s
^C

これをNanoPi NEOで動かすには

以下のようにARM用にビルドするだけでNano Pi NEOで動きました。同じバイナリをラズパイでも動かすことができるはずです。

$ GOARCH=arm GOARM=7 go build
$ file ./net_activity
./net_activity: ELF 32-bit LSB  executable, ARM, EABI5 version 1 (SYSV), statically linked, not stripped

関連

Golangで周期的に実行するときのパターン

4
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
10