如何使用Golang在Linux中获得网络速度

如何使用Golang在Linux中获得网络速度

伙计们,我正在阅读 / proc / net / dev 以获取接收和传输的字节
我能够计算in_traffic,out_traffic,但是Speed无法找到

delta_time是上次检查的unix时间与当前unix时间的黑白差

in_traffic = ( ( (new_inbytes - prev_inbytes) * 8 ) /  (delta_time) )
out_traffic = ( ( (new_outbytes -  prev_outbytes) * 8) / (delta_time))

if speed > 0{
        in_utilization = in_traffic / (speed * 10000)
        out_utilization = out_traffic / (speed * 10000)
    }

请帮忙,
谢谢

最佳答案

I am using CGO to get network speed.
package main


/*
#include <stdio.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <linux/sockios.h>
#include <linux/if.h>
#include <linux/ethtool.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

int get_interface_speed(char *ifname){
    int sock;
    struct ifreq ifr;
    struct ethtool_cmd edata;
    int rc;
    sock = socket(AF_INET, SOCK_STREAM, 0);
    // string copy first argument into struct
    strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
    ifr.ifr_data = &edata;
    // set some global options from ethtool API
    edata.cmd = ETHTOOL_GSET;
    // issue ioctl
    rc = ioctl(sock, SIOCETHTOOL, &ifr);

    close(sock);

    if (rc < 0) {
        perror("ioctl");        // lets not error out here
        // make sure to zero out speed
        return 0;
    }

    return edata.speed;
}
*/
import "C"

import (
    "fmt"
    "unsafe"
)

func main() {
    ifname := []byte("eth0\x00")// interface name eth0,eth1,wlan0 etc.
    sp := C.get_interface_speed((*C.char)(unsafe.Pointer(&ifname[0])))
    fmt.Println(sp)
}

Please give some suggestion .

关于networking - 如何使用Golang在Linux中获得网络速度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36262078/

10-09 14:03