内核空间中关于网络接口的信息

3

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

2个回答

2
你正在寻找 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中获取一些内容时,总是会得到“dereferencing pointer to incomplete type”的错误提示。 - Kalvy
@Kalvy,我已经编辑了我的答案;如果它是正确的话,我会感激你标记一下。谢谢。 - Oleksandr Kravchuk
你能告诉我IPv6地址确切的位置吗? - Kalvy

0
如果您在从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_dev上调用list_entry()来使用inet6_devaddr_list字段获取ipv6地址。实际上,addr_list.next字段嵌入在一个inet6_ifaddr结构体中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接