0

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?

firelynx
  • 30,616
  • 9
  • 91
  • 101
VladutZzZ
  • 680
  • 1
  • 8
  • 27
  • On a system with multiple physical interfaces, which one is the "real" address? – larsks Jun 15 '15 at 15:17
  • A computer does not have a MAC Address, a network card has a MAC address. You will always run the risk of having more than one. Do you want the MAC Address of the network card which is the default route maybe? Please explain better which one you want. – firelynx Jun 15 '15 at 15:17
  • @firelynx yes, the MAC Address of the network card which is the default route. – VladutZzZ Jun 15 '15 at 15:22
  • This is a very similar question http://stackoverflow.com/questions/159137/getting-mac-address – firelynx Jun 15 '15 at 15:27

1 Answers1

0

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
Community
  • 1
  • 1
gerosalesc
  • 2,983
  • 3
  • 27
  • 46