在C中以编程方式获取网络链接类型和速度 [英] Get network link type and speed programmatically in C

查看:91
本文介绍了在C中以编程方式获取网络链接类型和速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有更紧凑的方法来查找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.

提前谢谢!

解决方案

要获取链接类型(以太网,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,例如 解决方案

To get the link type (Ethernet, 802.11, etc.) you can use the SIOCGIFHWADDR ioctl. The ioctl returns one of ARPHRD_ values (defined in net/if_arp.h) in the sa_family of the struct sockaddr. See man netdevice(7) for more details.

See an example (not tested):

/**
 * 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;
}

To get the link speed you need the SIOCETHTOOL ioctl as discussed for example here.

这篇关于在C中以编程方式获取网络链接类型和速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆