network_stat.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package linux
  2. import (
  3. "io/ioutil"
  4. "strconv"
  5. "strings"
  6. )
  7. type NetworkStat struct {
  8. Iface string `json:"iface"`
  9. RxBytes uint64 `json:"rxbytes"`
  10. RxPackets uint64 `json:"rxpackets"`
  11. RxErrs uint64 `json:"rxerrs"`
  12. RxDrop uint64 `json:"rxdrop"`
  13. RxFifo uint64 `json:"rxfifo"`
  14. RxFrame uint64 `json:"rxframe"`
  15. RxCompressed uint64 `json:"rxcompressed"`
  16. RxMulticast uint64 `json:"rxmulticast"`
  17. TxBytes uint64 `json:"txbytes"`
  18. TxPackets uint64 `json:"txpackets"`
  19. TxErrs uint64 `json:"txerrs"`
  20. TxDrop uint64 `json:"txdrop"`
  21. TxFifo uint64 `json:"txfifo"`
  22. TxColls uint64 `json:"txcolls"`
  23. TxCarrier uint64 `json:"txcarrier"`
  24. TxCompressed uint64 `json:"txcompressed"`
  25. }
  26. func ReadNetworkStat(path string) ([]NetworkStat, error) {
  27. data, err := ioutil.ReadFile(path)
  28. if err != nil {
  29. return nil, err
  30. }
  31. lines := strings.Split(string(data), "\n")
  32. // lines[2:] remove /proc/net/dev header
  33. results := make([]NetworkStat, len(lines[2:])-1)
  34. for i, line := range lines[2:] {
  35. // patterns
  36. // <iface>: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  37. // or
  38. // <iface>:0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 (without space after colon)
  39. colon := strings.Index(line, ":")
  40. if colon > 0 {
  41. metrics := line[colon+1:]
  42. fields := strings.Fields(metrics)
  43. results[i].Iface = strings.Replace(line[0:colon], " ", "", -1)
  44. results[i].RxBytes, _ = strconv.ParseUint(fields[0], 10, 64)
  45. results[i].RxPackets, _ = strconv.ParseUint(fields[1], 10, 64)
  46. results[i].RxErrs, _ = strconv.ParseUint(fields[2], 10, 64)
  47. results[i].RxDrop, _ = strconv.ParseUint(fields[3], 10, 64)
  48. results[i].RxFifo, _ = strconv.ParseUint(fields[4], 10, 64)
  49. results[i].RxFrame, _ = strconv.ParseUint(fields[5], 10, 64)
  50. results[i].RxCompressed, _ = strconv.ParseUint(fields[6], 10, 64)
  51. results[i].RxMulticast, _ = strconv.ParseUint(fields[7], 10, 64)
  52. results[i].TxBytes, _ = strconv.ParseUint(fields[8], 10, 64)
  53. results[i].TxPackets, _ = strconv.ParseUint(fields[9], 10, 64)
  54. results[i].TxErrs, _ = strconv.ParseUint(fields[10], 10, 64)
  55. results[i].TxDrop, _ = strconv.ParseUint(fields[11], 10, 64)
  56. results[i].TxFifo, _ = strconv.ParseUint(fields[12], 10, 64)
  57. results[i].TxColls, _ = strconv.ParseUint(fields[13], 10, 64)
  58. results[i].TxCarrier, _ = strconv.ParseUint(fields[14], 10, 64)
  59. results[i].TxCompressed, _ = strconv.ParseUint(fields[15], 10, 64)
  60. }
  61. }
  62. return results, nil
  63. }