我正在编写一个报告本地计算机上网络设备属性的应用程序。我需要 mac 地址、mtu、链接速度和其他一些。我为此使用 udev。我已经想出了如何获取mac地址和mtu,但还没有弄清楚如何获取链接速度。我可以从终端使用 ethtool 获取它,但我需要一种以编程方式获取它的方法。
有谁知道如何使用 udev 或其他库获取链接速度属性?
最佳答案
您需要使用 SIOCETHTOOL
ioctl() 调用。有一个不错的introduction to ioctl/SIOCETHTOOL调用 LinuxJournal,下面的代码(这不是一个良好的 C 实践的例子!)应该向您展示如何使用它来获得速度。
#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>
int main (int argc, char **argv)
{
int sock;
struct ifreq ifr;
struct ethtool_cmd edata;
int rc;
sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
if (sock < 0) {
perror("socket");
exit(1);
}
strncpy(ifr.ifr_name, "eth0", sizeof(ifr.ifr_name));
ifr.ifr_data = &edata;
edata.cmd = ETHTOOL_GSET;
rc = ioctl(sock, SIOCETHTOOL, &ifr);
if (rc < 0) {
perror("ioctl");
exit(1);
}
switch (ethtool_cmd_speed(&edata)) {
case SPEED_10: printf("10Mbps\n"); break;
case SPEED_100: printf("100Mbps\n"); break;
case SPEED_1000: printf("1Gbps\n"); break;
case SPEED_2500: printf("2.5Gbps\n"); break;
case SPEED_10000: printf("10Gbps\n"); break;
default: printf("Speed returned is %d\n", edata.speed);
}
return (0);
}
关于linux - 以编程方式获取链接速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2872058/