Search code examples
linuxkernel-modulenetwork-interface

Is there a kernel module that returns exactly what a simple 'ifconfig' does?


I'm writing a kernel module that needs information about the local machine's interfaces just like the ones retuned by a simple 'ifconfig' command, I've searched a lot for it, but couldn't find anything


Solution

  • You can get all of that information through the struct net_device one way or another. As Albert Veli said, you can get this struct net_device pointer using __dev_get_by_name().

    If you tell us what information you need specifically we might even be able to point you to the correct fields.

    Finding the MAC address is fairly simple:

    struct net_device *dev = __dev_get_by_name("eth0");
    dev->dev_addr; // is the MAC address
    dev->stats.rx_dropped; // RX dropped packets. (stats has more statistics)
    

    Finding the IP address is rather harder, but not impossible:

    struct in_device *in_dev = rcu_dereference(dev->ip_ptr);
    // in_dev has a list of IP addresses (because an interface can have multiple)
    struct in_ifaddr *ifap;
    for (ifap = in_dev->ifa_list; ifap != NULL;
             ifap = ifap->ifa_next) {
        ifap->ifa_address; // is the IPv4 address
    }
    

    (None of this was compile tested, so typos are possible.)