Go-Linux获取网卡上下行速率
1. 前言
一般会有这么个小工具,可以显示电脑的cpu、内存、温度以及网络上下行流量速率,之前我们已经实现了go-linux查看cpu占用率、cpu温度、内存占用及磁盘占用率的方法,这里再总结一下计算网卡上下行速率的方法。
2. 实现思路
通过cat /proc/net/dev可以查看Linux上网络设备的流量信息,然后我们通过计算每秒的间隔值可以大致将其作为网络设备的流量速率。
2. 代码
直接上代码,计算后根据KB再做一下转换即可:
type ReceiveBytes uint64
type TransmitBytes uint64
type DownloadFlow string
type UploadFlow string
func UploadDownloadFlow(dev string) (DownloadFlow, UploadFlow, error) {
down, up, err := TotalFlowByDevice(dev)
if err != nil {
logger.Error(err)
return "", "", err
}
logger.Debug(down, up)
time.Sleep(time.Second * 1)
down2, up2, err := TotalFlowByDevice(dev)
if err != nil {
logger.Error(err)
return "", "", err
}
logger.Debug(down2, up2)
downStr := strconv.FormatInt(int64((down2-down)/1024), 10) + "Kbps"
upStr := strconv.FormatInt(int64((up2-up)/1024), 10) + "Kbps"
return DownloadFlow(downStr), UploadFlow(upStr), nil
}
func TotalFlowByDevice(dev string) (ReceiveBytes, TransmitBytes, error) {
devInfo, err := ioutil.ReadFile("/proc/net/dev")
if err != nil {
logger.Error(err)
return 0, 0, err
}
var receive int = -1
var transmit int = -1
var receiveBytes uint64
var transmitBytes uint64
lines := strings.Split(string(devInfo), "\n")
for _, line := range lines {
logger.Debug(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 {
//logger.Debug(value)
if receive == i {
bytes, _ := strconv.ParseInt(value, 10, 64)
receiveBytes = uint64(bytes)
} else if transmit == i {
bytes, _ := strconv.ParseInt(value, 10, 64)
transmitBytes = 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 {
//logger.Debug(value)
if strings.Contains(value, "bytes") {
if !tag {
tag = true
receive = index
} else {
transmit = index
}
}
index++
}
}
}
}
}
logger.Debug("receive_bytes :", receiveBytes)
logger.Debug("transmit_bytes :", transmitBytes)
return ReceiveBytes(receiveBytes), TransmitBytes(transmitBytes), nil
}
网页进行定时刷新或者主动上报。