Search code examples
pythondictionarypython-netifaces

Elegant way to access netifaces dictionaries


This might sound stupid but honestly I have no idea how to get it right. I am messing around in Python for some time now. I would like to get an access to a dictionary made by netifaces (Mac address of specific network card), import an entry and then print it as an elegant string. I have a problem of finding elegant way to do so.

Here's what I have so far:

>>>import netifaces
>>>netifaces.ifaddress('en3')

I get proper value of Mac address represented like this:

{18: [{'addr': '1a:00:00:f1:e5:b1'}]}

I need to import only Mac address part (as a string) so I tried to get it in some sort of elegant way but best I could do is:

>>>string = netifaces.ifaddress('en3')
>>>string[18]

And I get (as expected):

[{'addr': '1a:02:00:d1:e5:b1'}]

So here I decided to try some serious Inception-style coding which essentially works but it is definitely not elegant and simple...

>>>str=string[18]
>>>str[0]

So I get:

{'addr': '1a:00:00:f1:e5:b1'}

Then I did:

>>>s=str[0]
>>>s['addr']

Then I get (finally) my Mac address... Is there any elegant way of getting that Mac-address without making my code look like that?


Solution

  • First, don't name your variables string or str because now you're masking built-in python types and modules and some day that will bite you.

    Second, the keys in the dictionary returned by netiface.ifaddresses are protocol numbers, and there are named constants in the netifaces module for each of these. So instead of asking for result[17], ask for result[netifaces.AF_LINK].

    It seems like you're asking if you have to split up your code across multiple lines to get the value you want, the answer is no, you can do that all at once. E.g, to get the first MAC address of an interface:

    >>> import netifaces
    >>> result = netifaces.ifaddresses('eth0')
    >>> print result[netifaces.AF_LINK][0]['addr']
    c8:5b:76:14:59:ee
    

    Or even:

    >>> result = netifaces.ifaddresses('eth0')[netifaces.AF_LINK][0]['addr']
    >>> print result
    c8:5b:76:14:59:ee