package netstat import ( "encoding/json" "errors" "net/http" "os/exec" "runtime" "strconv" "strings" "imuslab.com/arozos/mod/common" ) func HandleGetNetworkInterfaceStats(w http.ResponseWriter, r *http.Request) { rx, tx, err := GetNetworkInterfaceStats() if err != nil { common.SendErrorResponse(w, err.Error()) return } currnetNetSpec := struct { RX int64 TX int64 }{ rx, tx, } js, _ := json.Marshal(currnetNetSpec) common.SendJSONResponse(w, string(js)) } //Get network interface stats, return rx_byte, tx_byte and error if any func GetNetworkInterfaceStats() (int64, int64, error) { if runtime.GOOS == "windows" { cmd := exec.Command("wmic", "path", "Win32_PerfRawData_Tcpip_NetworkInterface", "Get", "BytesReceivedPersec,BytesSentPersec,BytesTotalPersec") out, err := cmd.Output() if err != nil { return 0, 0, err } //Filter out the first line lines := strings.Split(strings.ReplaceAll(string(out), "\r\n", "\n"), "\n") if len(lines) >= 2 && len(lines[1]) >= 0 { dataLine := lines[1] for strings.Contains(dataLine, " ") { dataLine = strings.ReplaceAll(dataLine, " ", " ") } dataLine = strings.TrimSpace(dataLine) info := strings.Split(dataLine, " ") if len(info) < 3 { return 0, 0, errors.New("Invalid wmic results") } rxString := info[0] txString := info[1] rx := int64(0) tx := int64(0) if s, err := strconv.ParseInt(rxString, 10, 64); err == nil { rx = s } if s, err := strconv.ParseInt(txString, 10, 64); err == nil { tx = s } //log.Println(rx, tx) return rx, tx, nil } else { //Invalid data return 0, 0, errors.New("Invalid wmic results") } } else if runtime.GOOS == "linux" { } return 0, 0, errors.New("Platform not supported") }