Python windows下获取MAC地址的一种方法(转)

来源:互联网 发布:淘宝抠图出来衣服 编辑:程序博客网 时间:2024/05/21 18:22
转自:http://my.oschina.net/volash86/blog/335008
摘要
不使用UUID模块,也不使用popen方法

我最近有一个项目,使用Python在win32下开发一个COM组建,该COM组建其中一个方法是获取本地电脑的MAC地址。

需求很简单,虽然我是Python新手中的新手,但我还是会使用搜索引擎进行搜索。

百度一下,发现大部分都介绍使用import UUID获取MAC地址,或使用os.popen("ipconfig /all")的方式获取。而后者容易受到操作系统中英文环境影响。

如这篇文章:http://www.cnblogs.com/Jerryshome/archive/2011/11/30/2269365.html

所以,我很乖的使用了被大部分网页推荐的第一种方法,

def get_mac_address():    import uuid    node = uuid.getnode()    mac = uuid.UUID(int = node).hex[-12:]    return mac

很幸运,直接能用。

然后用C++编写一个访问COM的程序。

但问题来了(我不会问学挖掘机哪家强的-_-///)

居然弹出C RUNTIME Error!!

---------------------------Microsoft Visual C++ Runtime Library---------------------------Runtime Error!Program: E:\Blender Foundation\blender.exeR6034An application has made an attempt to load the C runtime library incorrectly.Please contact the application's support team for more information.

虽然功能能正常使用,但老是弹出这个对话框很不爽!

WINXP/WIN7 32位均出现该问题!!

经过一通科学上网,在如下网页发现:

https://developer.blender.org/T27666

导入UUID后,被C/C++等程序调用PYTHON程序,均会提示该问题,该bug未fixed掉,目前未有好的解决方案。原因是:ctypes loads wrong version of C runtime, leading to error message box from system

官网的buglist为:http://bugs.python.org/issue17213

OK,居然官网都没法解决,那只能换种方法了。

有经过一轮科学上网后,找到netifaces库,该方法和UUID一样,能通用的获取MAC地址。

库地址:https://pypi.python.org/pypi/netifaces

里面有相关教程,很简单,我贴出我写的demo程序,如下:

def networkinfo(self):    import netifaces    devlist = []    tempList = []    tmpdict = {}    devices = netifaces.interfaces()    for dev in devices:        devlist.append(dev)                for devinfo in devlist:        infos = netifaces.ifaddresses(devinfo)        if len(infos) < 2:            continue        ip = infos[netifaces.AF_INET][0]['addr']        if ip != '':            if ip != '127.0.0.1':                tmpdict["ip"] = ip                tmpdict["mac"] = infos[netifaces.AF_LINK][0]['addr']                break                    tempList.append(tmpdict)        return tempList

我这里获取了本地电脑的网络IP和该IP的网卡MAC地址。细节不做介绍了,大家可以看官网介绍。

0 0
原创粉丝点击