linux 下C語言實現 讀取網絡卡速度

2021-05-22 23:25:06 字數 2737 閱讀 4516

這幾天要寫乙個監控之類東東,其中網絡卡一項要計算利用率,那就要取得網絡卡本身速度才能計算出來,本來想用perl實現,但發現網上沒有現成的東東,後來幾經輾轉,最後想起ethtool能取到,就參考了此原始碼,貼出來供大家以後有個思路吧,

有時間再轉成perl的:)

直接編譯命令:gcc -p -g  getnet.c && gcc -o getnet getnet.c && ./getnet eth0

原始碼如下:

// filename: getnet.c

// command sample: ./getnet eth0

// compile command: gcc -p -g getnet.c && gcc -o getnet getnet.c

#include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef siocethtool

#define siocethtool 0x8946

#endif

#ifndef array_size

#define array_size(x) (sizeof(x) / sizeof((x)[0]))

#endif

/* cmds currently supported */

#define ethtool_gset 0x00000001 /* get settings. */

#define ethtool_sset 0x00000002 /* set settings. */

/* hack, so we may include kernel's ethtool.h */

//typedef unsigned long long __u64;

typedef __uint32_t __u32; /* ditto */

typedef __uint16_t __u16; /* ditto */

typedef __uint8_t __u8; /* ditto */

/* the forced speed, 10mb, 100mb, gigabit, 2.5gb, 10gbe. */

#define speed_10 10

#define speed_100 100

#define speed_1000 1000

#define speed_2500 2500

#define speed_10000 10000

/* this should work for both 32 and 64 bit userland. */

struct ethtool_cmd ;

int main(int argc, char *argp)

char *devname;

devname = argp[1] ; // 取得網絡卡名

//devname = "eth0" ; // 取得網絡卡名

ifreq結構定義在/usr/include\net/if.h,用來配置ip位址,啟用介面,配置mtu等介面資訊的。

其中包含了乙個介面的名字和具體內容——(是個共用體,有可能是ip位址,廣播位址,子網掩碼,mac號,mtu或其他內容)。

ifreq包含在ifconf結構中。而ifconf結構通常是用來儲存所有介面的資訊的。

*/ struct ifreq ifr, *ifrp; // 介面請求結構

int fd; // to access socket 通過socket訪問網絡卡的 檔案描述符號fd

/* setup our control structures. */

memset(&ifr, 0, sizeof(ifr));

strcpy(ifr.ifr_name, devname);

/* open control socket. */

fd = socket(af_inet, sock_dgram, 0);

if (fd < 0)

int err;

struct ethtool_cmd ep;

//fprintf(stdout, "settings for %s:\n", devname);

ep.cmd = ethtool_gset; // ethtool-copy.h:380:#define ethtool_gset 0x00000001 /* get settings. */

ifr.ifr_data = (caddr_t)&ep; // caddr_t 是void型別,而這句話是什麼意思

err = ioctl(fd, siocethtool, &ifr); // int ioctl(int handle, int cmd,[int *argdx, int argcx]);

if (err != 0)

// **********= 輸出 網絡卡速度;**********==

fprintf(stdout, "%s speed: ", devname );

switch (ep.speed) ;

return 0;

}

Linux下C語言實現CopyFile

linux下c語言實現檔案拷貝 function copy file from file1 to file2 how to execute copyfile file1 file2 under linux data 2007 05 09 include fprintf stderr,bufsiz i...

Linux下C語言實現UDP Socket程式設計

該博文參考了linux c socket 程式設計之udp一文,在這裡表示感謝!傳送方 file udp sender.c author henry created on 2019年5月29日17 08 13 主要實現 傳送20個文字訊息,然後再傳送乙個終止訊息 include include in...

C語言實現linux網絡卡檢測 改進版

c語言 shell 實現linux網絡卡狀態檢測 和 c語言實現linux網絡卡連線檢測 2文的方法各有缺陷,比如有些系統執行ifconfig需要root許可權,要不就不支援ioctl fd,siocgmiiphy,ifr 這樣的操作。以下給出了c語言實現linux網絡卡連線檢測 的改進版實現與c語...