網絡卡裝置資訊獲取

2021-08-25 22:26:01 字數 2232 閱讀 1421

網絡卡工作在osi七層協議中的鏈路層,是主機與網路對接的重要介面,它完成了網路連線的物理和電訊號之間的轉換,同時還對網路資料報幀進行傳送、接收、校驗等,是上層網路應用的基石。在計算機架構中,通常是cpu通過內部匯流排(ahb bus 或者 pci bus)與mac控制單元通訊,然後由mac控制單元通過mii介面協議與phy裝置進行資料互動,phy裝置則負責與外部網路通訊(rj45網路介面)。通常將mac控制單元與phy裝置整合在一起,構成我們所熟悉的網絡卡(ethn裝置),在嵌入式開發中,經常需要獲取網絡卡裝置的一些資訊,比如說網絡卡的工作模式、網絡卡的頻寬等等,雖然有現成的ethtool等開源軟體來實現,但是對於儲存空間有限的嵌入式裝置,我們可以通過**寫socket然後ioctl來實現。下圖是參考了網友的mac控制單元與phy裝置的功能框圖

先來了解一下網絡卡裝置資訊的結構體內容,裡面包括了我們所熟知的網絡卡模式支援,網絡卡特性、網絡卡頻寬、全雙工模式、phy位址等等網絡卡資訊。

struct ethtool_cmd ;
獲取網絡卡資訊的樣例如下,它的實現也很簡單,首先建立乙個udp socket,然後對資料進行組裝,最後通過ioctl介面來獲取網絡卡的資訊。

#include #include #include #include #include #include #include #include #include #include #include #include #include #define speed_10        10  

#define speed_100 100

#define speed_1000 1000

#define speed_2500 2500

#define speed_10000 10000

#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. */

typedef __uint32_t __u32; /* ditto */

typedef __uint16_t __u16; /* ditto */

typedef __uint8_t __u8; /* ditto */

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

struct ethtool_cmd ;

int get_netcard_speed(char *eth_name)

struct ethtool_cmd ep;

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

ifr.ifr_data = (caddr_t)&ep;

ret = ioctl(fd, siocethtool, &ifr);

if (ret != 0)

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

switch (ep.speed)

close(fd);

return 0;

} int main(int argc, char* argv)

在ubuntu16.04下執行的樣例列印輸出

在一些嵌入式裝置中常常需要對網絡卡裝置資訊獲取,以對裝置的網路執行環境有所了解,不過現在的網絡卡大多數支援全雙工,10m/100m/1000m模式自適應,很少再需要使用者進行手動干預。最近工作中遇到了ma控制c單元與phy裝置配置的一些問題,參考了一些資料,做了一些整理成此文,以作備忘。

參考文章

獲取網絡卡資訊

在windows中獲取網路介面卡相關資訊是很方便的,可以通過getadaptersinfo函式獲取並儲存在ip adapter info結構體中,再對結構休進行解析得到介面卡資訊。有關函式和結構體的詳細說明可以參考msdn,這裡就不再複述。下面直接給出具體示例程式。引入標頭檔案 include in...

linux 獲取網絡卡資訊

sar n dev 2 10 41 37 am iface rxpck s txpck s rxkb s txkb s rxcmp s txcmp s rxmcst s 10 41 39 am eth0 1.50 1648.00 0.15 117.54 0.00 0.00 1.00 10 41 39...

獲取iOS裝置資訊

鑌哥就直接寫 了 獲取手機資訊 應用程式的名稱和版本號等資訊都儲存在mainbundle的乙個字典中,用下面 可以取出來 nsdictionary infodict nsbundle mainbundle infodictionary nsstring versionnum infodict obj...