GO 获取指定网卡流量

func TotalFlowByDevice(dev string) uint64 {
	devinfo, err := ioutil.ReadFile("/proc/net/dev")
	if err != nil {
		return 0
	}

	var receive int = -1
	var transmit int = -1

	var receive_bytes uint64
	var transmit_bytes uint64

	lines := strings.Split(string(devinfo), "\n")
	for _, line := range lines {
		//fmt.Println("line :", line)
		if strings.Contains(line, dev) {
			i := 0
			fields := strings.Split(line, ":")
			for _, field := range fields {
				if strings.Contains(field, dev) {
					i = 1
				} else {
					values := strings.Fields(field)
					for _, value := range values {
						//fmt.Println("value :", value)
						if receive == i {
							bytes, _ := strconv.ParseInt(value, 10, 64)
							receive_bytes = uint64(bytes)
						} else if transmit == i {
							bytes, _ := strconv.ParseInt(value, 10, 64)
							transmit_bytes = uint64(bytes)
						}
						i++
					}
				}
			}
		} else if strings.Contains(line, "face") {
			index := 0
			tag := false
			fields := strings.Split(line, "|")
			for _, field := range fields {
				if strings.Contains(field, "face") {
					index = 1
				} else if strings.Contains(field, "bytes") {
					values := strings.Fields(field)
					for _, value := range values {
						//fmt.Println("value :", value)
						if strings.Contains(value, "bytes") {
							if !tag {
								tag = true
								receive = index
							} else {
								transmit = index
							}
						}
						index++
					}
				}
			}
		}
	}
	//fmt.Println("receive :", receive)
	//fmt.Println("transmit :", transmit)
	//fmt.Println("receive_bytes :", receive_bytes)
	//fmt.Println("transmit_bytes :", transmit_bytes)

	return receive_bytes + transmit_bytes
}

 

你可能感兴趣的:(GO)