networking - 如何使用golang在linux中获取网络速度

标签 networking go

伙计们,我正在阅读 /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/

相关文章:

amazon-web-services - k8s 使用 OwnerRef 获取集群中的所有 pod 层次结构

image - 在 go (golang) 中显示图像

go - 如何在 Go 中处理大整数?

c# - RDM 套接字

unity-game-engine - 为客户端分配颜色(网络)

c - 没有 "Windows Security Alert"的网络程序

sockets - 如何使用 std.socket 和 std.socketstream? (D 编程语言 2.x)

C++ 风格的 Golang 迭代器

go - godoc 可播放示例上的 "cannot find package"错误

c - 使用 poll() 运行一个简单的 TCP 服务器,如何触发事件 "artificially"?