golang计算主机的访问流量和发送流量

package main

import (
	"fmt"
	"github.com/mackerelio/go-osstat/network"
	"time"
)

func main() {
    
    
	CounterReceiveFlow()
}

// CounterReceiveFlow 计算每秒的访问流量
func CounterReceiveFlow() int {
    
    
	// 获取起始时间点的网络计数器
	beforeStats, err := network.Get()
	if err != nil {
    
    
		fmt.Printf("get before network counter failed, err: %v\n", err)
		return 0
	}

	// 等待1秒钟
	time.Sleep(1 * time.Second)

	// 获取结束时间点的网络计数器
	afterStats, err := network.Get()
	if err != nil {
    
    
		fmt.Printf("get after network counter failed, err: %v\n", err)
		return 0
	}

	// 计算起始时间点的接收、发送数据的总量
	beforeTxBytes := 0
	beforeRxBytes := 0
	for _, item := range beforeStats {
    
    
		beforeTxBytes += int(item.TxBytes)
		beforeRxBytes += int(item.RxBytes)
	}
	// 计算结束时间点的接收、发送数据的总量
	afterTxBytes := 0
	afterRxBytes := 0
	for _, item := range afterStats {
    
    
		afterTxBytes += int(item.TxBytes)
		afterRxBytes += int(item.RxBytes)
	}

	// 计算接收流量
	receiveFlow := afterRxBytes - beforeRxBytes
	fmt.Println(receiveFlow)
	// 计算发送流量
	//sendFlow := afterTxBytes - beforeTxBytes
	//fmt.Println(sendFlow)
	return receiveFlow
}

猜你喜欢

转载自blog.csdn.net/SweetHeartHuaZai/article/details/132909546