【问题标题】:Information about network interface in kernel space有关内核空间中网络接口的信息
【发布时间】:2016-01-09 22:46:47
【问题描述】:

我如何在内核空间中获取有关eth0 的信息?我需要知道它是启用还是禁用,是否设置了 ipv6(当然还有 ipv6)。

【问题讨论】:

    标签: linux-kernel network-programming


    【解决方案1】:

    您正在寻找struct net_device:

    #include <linux/netdevice.h>
    
    struct net_device *net_dev = __dev_get_by_name("eth0");
    
    net_dev->flags; // IFF_UP will be set if an interface active (up)
    

    要获取 IPv6 地址,你需要从你的 net_device 中获取struct inet6_dev,并从中获取 IP 地址:

    #include <net/addrconf.h>
    #include <net/if_inet6.h>
    
    struct inet6_dev *net_dev6 = in6_dev_get(net_device);
    

    【讨论】:

    • 谢谢,这是有效的解决方案。但是我仍然无法弄清楚如何获得 ipv6 地址。我尝试了类似的方法: void get_ipv6(char * buf){ struct net_device *dev; dev = _dev_get_by_name("eth0"); sprintf(buf, "%pI6", dev->ip6_ptr->something); //我不知道确切的字段}当我想从 ip6_ptr 获取某些东西时,我总是得到“取消引用指向不完整类型的指针”
    • @Kalvy 我已经编辑了我的答案;如果是这种情况,如果您将其标记为正确,我将不胜感激。谢谢。
    • 你能告诉我ip6v地址的确切位置吗?
    【解决方案2】:

    如果您无法从inet6_dev 实例获取 ipv6 地址,您可以在内核源代码中找到一些线索

    (https://elixir.bootlin.com/linux/latest/source/net/ipv6/addrconf.c)

    static void ipv6_link_dev_addr(struct inet6_dev *idev, struct inet6_ifaddr *ifp) {
        struct list_head *p;
        int ifp_scope = ipv6_addr_src_scope(&ifp->addr);
    
        /*
         * Each device address list is sorted in order of scope -
         * global before linklocal.
         */
        list_for_each(p, &idev->addr_list) {
            struct inet6_ifaddr *ifa
                = list_entry(p, struct inet6_ifaddr, if_list);
            if (ifp_scope >= ipv6_addr_src_scope(&ifa->addr))
                break;
        }
    
        list_add_tail_rcu(&ifp->if_list, p);
    }
    

    从上面的代码可以清楚地看出,inet6_devaddr_list 字段可以通过在inet6_dev::addr_list.next 上调用list_entry() 来获取ipv6 地址。 addr_list.next 字段实际上嵌入在 inet6_ifaddr 结构中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-14
      相关资源
      最近更新 更多