package main import ( "fmt" "github.com/axgle/mahonia" "github.com/shirou/gopsutil/net" nnet "net" "os" "os/exec" "strings" "time" ) var debug string func main() { if len(os.Args) != 3 && len(os.Args) != 4 { fmt.Println("Args error ...") return } R_name := strings.ToUpper(os.Args[1]) I_name := strings.ToUpper(os.Args[2]) if len(os.Args) == 4 { debug = os.Args[3] } var addr string lis, _ := nnet.Interfaces() for _, v := range lis { if strings.ToUpper(v.Name) == R_name { addr = v.HardwareAddr.String() } if debug == "true" { fmt.Println(v) } } if len(addr) == 0 { addr = cmd_get_mac(R_name) if len(addr) < 2 { return } } var num []uint64 = make([]uint64, 2) for i := 0; i < 2; i++ { Netio, err := net.NetIOCounters(true) if err != nil { fmt.Println(err) return } for _, v := range Netio { if debug == "true" { fmt.Printf("HardWare Addr :%s\n%s\n", addr, nnet.HardwareAddr(v.Addr[:8]).String()) fmt.Println(v) } if strings.Contains(nnet.HardwareAddr(v.Addr[:8]).String(), addr) { switch I_name { case "IN": num[i] = v.BytesRecv case "OUT": num[i] = v.BytesSent } } } if i == 1 { break } time.Sleep(5e9) } if debug == "true" { fmt.Println(num) } fmt.Print((num[1] - num[0]) / 5.00) } func cmd_get_mac(name string) string { cmd := exec.Command("getmac", "/FO", "csv", "/v", "/NH") buf, err := cmd.Output() if err != nil { if debug == "true" { fmt.Println(err) } return "" } s := mahonia.NewDecoder("gb18030").ConvertString(string(buf)) for _, v := range strings.Split(s, "\n") { if strings.Contains(v, name) { hwaddr, err := nnet.ParseMAC(split(v)) if err != nil && debug == "true" { fmt.Println(err) continue } return hwaddr.String() } } return "" } func split(s string) string { lis := strings.Split(s, ",") if len(lis) < 3 { return "" } return strings.Trim(lis[2], `"`) }
版权声明:本文为博主原创文章,未经博主允许不得转载。
有疑问加站长微信联系(非本文作者)