pythonpython-netifaces

interfaces eth0 nothing en0 list error for mac os


import netifaces as ni
ip = ni.ifaddresses("eth0")[ni.AF_INET]['addr']

error

ip = ni.ifaddresses("eth0")[ni.AF_INET]['addr'] ValueError: You must specify a valid interface name.

ip = ni.ifaddresses("en0")[ni.AF_INET]['addr']

error

ip = ni.ifaddresses("en0")[ni.AF_INET]['addr'] TypeError: list indices must be integers or slices, not str

Does anyone know why the mac is giving such errors?


Solution

  • The first error means that there is no interface named eth0. Indeed, this is a common interface name on Linux, but not on MacOS.

    The second error means that you are trying to extract a field which doesn't exist. There is information about en0 but it is an array, not a dict. This is like saying "hello"["addr"], there is no way to access the "addr":th element of a sequence. You apparently mean something like

    ip = ni.ifaddresses("en0")[ni.AF_INET][0]['addr']
    

    though there is no way out of context to tell whether getting only one address is actually what you want. The array you get represents a number of bindings; perhaps you want all of them?

    addrs = ni.ifaddresses('en0')
    ips = [x['addr'] for x in addrs[ni.AF_INET]]
    

    The netifaces documentation actually explains this in quite some detail.