Get MAC address of NIC that has the default route

670 views Asked by At

I need to find the MAC address of the Network Interface Card which is assigned the default route in python. with Python. For now i tried solution:

process = os.popen('wmic nic get MACAddress')
result = process.read()
process.close()
print result.split("  \r\n")[1:-1][0]

or:

from uuid import getnode as get_mac
':'.join(("%012X" % mac)[i:i+2] for i in range(0, 12, 2))

It's working when i have only 1 lan, but when i have some wmware adapter with some MAC, sometime i get that MAC.

How to get the MAC Address of the default route?

1

There are 1 answers

2
gerosalesc On

As @fyrelinx stated there is no "REAL" MAC address, but you can get the interface with the default route via the command line of your operating system using sub process module, the next command works on OSX:

>>> subprocess.call(["route", "-n", "get", "default"])
   route to: default
destination: default
       mask: default
    gateway: 192.168.0.1
  interface: **en1**
      flags: <UP,GATEWAY,DONE,STATIC,PRCLONING>
 recvpipe  sendpipe  ssthresh  rtt,msec    rttvar  hopcount      mtu     expire
       0         0         0         0         0         0      1500         0

Then you can get the mac address of that particular interface ('en1' in my case) using netifaces on pypi as seen in this discussion:

import netifaces as nif


netifaces.ifaddresses('en1')
try:
    if_mac = addrs[nif.AF_LINK][0]['addr']
except IndexError, KeyError:
    pass