在 Linux 系统中,可以使用 ethtool 工具获取网卡的网速、双工模式以及自动协商状态。以下是具体步骤和示例:

一、使用ethtool获取网卡信息
1、获取网卡信息
ethtool eth0 Settings for eth0: Supported ports: [ TP ] Supported link modes: 10baseT/Half 10baseT/Full 100baseT/Half 100baseT/Full 1000baseT/Full Supported pause frame use: No Supports auto-negotiation: Yes Advertised link modes: 1000baseT/Full Advertised pause frame use: No Advertised auto-negotiation: Yes Link partner advertised link modes: 100baseT/Half 100baseT/Full 1000baseT/Full Link partner advertised pause frame use: No Link partner advertised auto-negotiation: Yes Speed: 1000Mb/s Duplex: Full Port: Twisted Pair PHYAD: 1 Transceiver: internal Auto-negotiation: onMDI-X: Unknown
关键字段解释:
Speed: 当前网卡的连接速率,例如 1000Mb/s 表示 1Gbps。
Duplex: 当前的双工模式,Full 表示全双工,Half 表示半双工。
Auto-negotiation: 当前的自动协商状态,on 表示已启用,off 表示未启用。
Advertised link modes: 网卡当前支持的链路模式。
Link partner advertised link modes: 对端设备支持的链路模式。
2、提取网速、双工模式和自动协商状态
如果只想提取特定字段,可以使用 grep 和 awk 命令
ethtool eth0 | grep -E "Speed|Duplex|Auto-negotiation" Speed: 1000Mb/s Duplex: Full Auto-negotiation: on
2、参考:实时网速
如果需要实时查看网卡的传输速率,可以使用 nload 或 iftop 工具:
二、使用代码获取网卡信息
1、获取网卡连接状态
int res; struct ifreq ifr; struct ethtool_cmd edata;
memset(&ifr, 0, sizeof(struct ifreq)); memset(&edata, 0, sizeof(struct ethtool_cmd)); strncpy(ifr.ifr_name, NIC, sizeof(ifr.ifr_name)); edata.cmd = ETHTOOL_GLINK; ifr.ifr_data = (char *) &edata; res = ioctl(sockStatus, SIOCETHTOOL, &ifr); if (0 != res) { printf("failed to read Ethernet link state"); return -1; } pStateLink = (((struct ethtool_value *) &edata)->data); printf("---------->>>> link status %d \n", pStateLink );
3、获取网卡支持网速
if (edata.supported & SUPPORTED_1000baseT_Half) { printf("SUPPORTED_1000baseT_Half \n"); } if (edata.supported & SUPPORTED_1000baseT_Full) { printf("SUPPORTED_1000baseT_Full \n"); } if (edata.supported & SUPPORTED_100baseT_Half) { printf("SUPPORTED_100baseT_Half \n"); } if (edata.supported & SUPPORTED_100baseT_Full) { printf("SUPPORTED_100baseT_Full \n"); } if (edata.supported & SUPPORTED_10baseT_Half) { printf("SUPPORTED_10baseT_Half \n"); } if (edata.supported & SUPPORTED_10baseT_Full) { printf("SUPPORTED_10baseT_Full \n");}
4、获取网卡双工模式
res = ioctl(sockStatus, SIOCETHTOOL, &ifr); if (0 != res) { printf("failed to read Ethernet duplex setting"); return -1; } if (duplex != edata.duplex) { if (duplexNext != edata.duplex) { duplexNext = edata.duplex; }else{ printf("not DUPLEX_HALF\n"); }}
5、获取网卡自动协商是否支持
res = ioctl(sockStatus, SIOCETHTOOL, &ifr); if (0 != res) { printf("failed to read Autonegotiation status"); return -1; } if (AUTONEG_ENABLE == edata.autoneg) { printf("GOAL_ETH_AUTONEG_ON \n"); } else { printf("GOAL_ETH_AUTONEG_OFF \n"); }
欢迎关注:
1233

被折叠的 条评论
为什么被折叠?



