【问题标题】:Get network link type and speed programmatically in C在 C 中以编程方式获取网络链接类型和速度
【发布时间】:2012-05-27 22:58:14
【问题描述】:

我想知道是否有一种更简洁的方法可以在 Linux 中找到链接速度和网络接口的类型(无线、以太网),而不仅仅是打开并读取 /sys/class/net/eth0/type/sys/class/net/eth0/speed 文件。

如果没有,谁能告诉我在哪里可以找到/sys/class/net/eth0/type 返回的数字,对应于哪些网络类型?

编辑:情况变得更糟!经过一些无线实验后,/sys/class/net/wlan0/type 也返回 1,而/sys/class/net/wlan0/speed 不存在,我不得不从/sys/class/net/wlan0/wireless/link 获取链接速度,这有时会返回不正确的速度。例如,在 54Mbits 卡中有时会返回 55。

提前致谢!

【问题讨论】:

  • 有人在这里问过类似的问题:stackoverflow.com/questions/2872058/…
  • 是的,但是这个问题与以太网的速度有关。就我而言,链接也是无线的。不管怎样,我想我找到了办法。当我完成我的程序时,我会发布它。
  • 你有没有为这个工作找到解决方案?
  • 不幸的是,我结束了对 iw 和 ethtool 的输出的解析...不是最好的解决方案,但我没有空闲时间...

标签: c linux networking network-programming


【解决方案1】:

这只能解决一半的问题,但是使用库 libpcap,您可以打开一个实时 pcap_t,然后调用 pcap_datalink。这将为您提供链接类型。 (DLT_IEEE802_11、DLT_EN10MB 等)

【讨论】:

  • 我认为链路类型 DLT_IEEE802_11 只有在接口处于监控模式时才可用。否则 libpcap 将其作为标准以太网链接返回。但我会试试看,只是为了确定!谢谢!
【解决方案2】:

要获取链接类型(以太网、802.11 等),您可以使用SIOCGIFHWADDR ioctl。 ioctl 在struct sockaddrsa_family 中返回ARPHRD_ 值之一(在net/if_arp.h 中定义)。详情请见man netdevice(7)

查看示例(未测试):

/**
 * Get network interface link type
 * @param name the network interface name
 * @return <0 error code on error, the ARPHRD_ link type otherwise
 */
int get_link_type(const char* name)
{
    int rv;
    int fd;
    struct ifreq ifr;

    if (strlen(name) >= IFNAMSIZ) {
        fprintf(stderr, "Name '%s' is too long\n", name);
        return -ENAMETOOLONG;
    }
    strncpy(ifr.ifr_name, name, IFNAMSIZ);

    fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
    if (fd < 0)
        return fd;

    rv = ioctl(fd, SIOCGIFHWADDR, &ifr);
    close(fd);
    if (rv < 0)
        return rv;

    {
        char *type = "Unknown";
        switch (ifr.ifr_hwaddr.sa_family)
        {
        case ARPHRD_ETHER:  type = "Ethernet"; break;
        case ARPHRD_IEEE80211:  type = "802.11"; break;
        /* add more cases here */
        }
        printf("Link type is: %s\n", type);
    }

    return ifr.ifr_hwaddr.sa_family;
}

要获得链接速度,您需要 SIOCETHTOOL ioctl,例如 here

【讨论】:

    猜你喜欢
    • 2011-02-21
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2013-10-09
    • 2011-04-24
    • 2015-06-21
    • 1970-01-01
    相关资源
    最近更新 更多