Tuesday, February 6, 2024

[SOLVED] Getting the permanent address of an ethernet device

Issue

I'm looking for a way to retrieve the permanent address of an ethernet device in Python(3).

I've looked at various ways to do this:

  • Here's href="https://github.com/al45tair/netifaces" rel="nofollow noreferrer">netifaces, a Python library that can retrieve MAC addresses. Sadly, it's not able to fetch the permanent address of a device. so it can be overwritten

  • Here's python-ethtool. This does what I want, but it's deprecated and won't run with Python3 on the specific machine I'm developing for.

  • Then of course, I could just call ethtool -P from the command line (within Python, using subprocess) and read the output.

I've looked at the code for ethtool, and the information I need seems to live in a field of struct dev called perm_addr:

static int ethtool_get_perm_addr(struct net_device *dev, void __user *useraddr)
{
    struct ethtool_perm_addr epaddr;

    if (copy_from_user(&epaddr, useraddr, sizeof(epaddr)))
        return -EFAULT;

    if (epaddr.size < dev->addr_len)
        return -ETOOSMALL;
    epaddr.size = dev->addr_len;

    if (copy_to_user(useraddr, &epaddr, sizeof(epaddr)))
        return -EFAULT;
    useraddr += sizeof(epaddr);
    if (copy_to_user(useraddr, dev->perm_addr, epaddr.size))
        return -EFAULT;
    return 0;
}

How can I access this information in Python? I'd prefer an all Python solution over opening a subprocess and calling ethtool.


Solution

It is available through the file /sys/class/net/<iface>/address. The file /sys/class/net/<iface>/addr_assign_type indicates the type of address.

See https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-net, and look for 'permanent' in that document.



Answered By - user2849202
Answer Checked By - Mary Flores (WPSolving Volunteer)