Get MAC address of NIC that has the default route

时间:2015-06-15 15:13:32

标签: python mac-address wmic

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 个答案:

答案 0 :(得分:0)

正如@fyrelinx所说,没有" REAL" MAC地址,但您可以使用sub process模块通过操作系统的命令行获取默认路由的接口,下一个命令适用于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

然后你可以使用netifaces on pypi中的 this discussion 来获取该特定界面的mac地址(在我的情况下为&#39; en1&#39;)< / p>

import netifaces as nif


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