netstat.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package netstat
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "net/http"
  6. "os/exec"
  7. "runtime"
  8. "strconv"
  9. "strings"
  10. "imuslab.com/arozos/mod/common"
  11. )
  12. func HandleGetNetworkInterfaceStats(w http.ResponseWriter, r *http.Request) {
  13. rx, tx, err := GetNetworkInterfaceStats()
  14. if err != nil {
  15. common.SendErrorResponse(w, err.Error())
  16. return
  17. }
  18. currnetNetSpec := struct {
  19. RX int64
  20. TX int64
  21. }{
  22. rx,
  23. tx,
  24. }
  25. js, _ := json.Marshal(currnetNetSpec)
  26. common.SendJSONResponse(w, string(js))
  27. }
  28. //Get network interface stats, return rx_byte, tx_byte and error if any
  29. func GetNetworkInterfaceStats() (int64, int64, error) {
  30. if runtime.GOOS == "windows" {
  31. cmd := exec.Command("wmic", "path", "Win32_PerfRawData_Tcpip_NetworkInterface", "Get", "BytesReceivedPersec,BytesSentPersec,BytesTotalPersec")
  32. out, err := cmd.Output()
  33. if err != nil {
  34. return 0, 0, err
  35. }
  36. //Filter out the first line
  37. lines := strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n")
  38. if len(lines) >= 2 && len(lines[1]) >= 0 {
  39. dataLine := lines[1]
  40. for strings.Contains(dataLine, " ") {
  41. dataLine = strings.ReplaceAll(dataLine, " ", " ")
  42. }
  43. dataLine = strings.TrimSpace(dataLine)
  44. info := strings.Split(dataLine, " ")
  45. if len(info) < 3 {
  46. return 0, 0, errors.New("Invalid wmic results")
  47. }
  48. rxString := info[0]
  49. txString := info[1]
  50. rx := int64(0)
  51. tx := int64(0)
  52. if s, err := strconv.ParseInt(rxString, 10, 64); err == nil {
  53. rx = s
  54. }
  55. if s, err := strconv.ParseInt(txString, 10, 64); err == nil {
  56. tx = s
  57. }
  58. //log.Println(rx, tx)
  59. return rx, tx, nil
  60. } else {
  61. //Invalid data
  62. return 0, 0, errors.New("Invalid wmic results")
  63. }
  64. } else if runtime.GOOS == "linux" {
  65. }
  66. return 0, 0, errors.New("Platform not supported")
  67. }