2016-03-28 59 views
-1

傢伙我讀的/ proc /淨/ dev的用於接收和發送的字節 我能夠計算in_traffic,out_traffic而且速度獲得網絡速度在linux無法找到如何使用golang

delta_time是差的b/W上次檢查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) 
    } 

請幫忙,謝謝

回答

-1
What:  /sys/class/net/<iface>/speed 
Date:  October 2009 
KernelVersion: 2.6.33 
Description: 
     Indicates the interface latest or current speed value. Value is 
     an integer representing the link speed in Mbits/sec. 

     Note: this attribute is only valid for interfaces that implement 
     the ethtool get_settings method (mostly Ethernet). 
+0

這不是一個答案,它甚至不上大多數接口(例如,它不適合我的無線工作,也沒有內置以太網)工作。 – OneOfOne

+1

@OneOfOne:這是唯一的答案。你不能做得更好。 – peterSO

+0

@oneofone,任何建議,請如何獲得網絡速度,請幫助 – GKV

1
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 .