本文主要是介绍python取本地mac地址,ip地址,非ipconfig方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原于http://bytes.com/topic/python/answers/435474-how-get-local-mac-address
多个网卡没试过,但虚拟出来的能正确识别真正物理网卡
import ctypes
import socket
import structdef get_macaddress(host):""" Returns the MAC address of a network host, requires >= WIN2K."""# Check for api availabilitytry:SendARP = ctypes.windll.Iphlpapi.SendARPexcept:raise NotImplementedError('Usage only on Windows 2000 and above')# Doesn't work with loopbacks, but let's try and help.if host == '127.0.0.1' or host.lower() == 'localhost':host = socket.gethostname()# gethostbyname blocks, so use it wisely.try:inetaddr = ctypes.windll.wsock32.inet_addr(host)if inetaddr in (0, -1):raise Exceptionexcept:hostip = socket.gethostbyname(host)inetaddr = ctypes.windll.wsock32.inet_addr(hostip)buffer = ctypes.c_buffer(6)addlen = ctypes.c_ulong(ctypes.sizeof(buffer))if SendARP(inetaddr, 0, ctypes.byref(buffer), ctypes.byref(addlen)) != 0:raise WindowsError('Retreival of mac address(%s) - failed' % host)# Convert binary data into a string.macaddr = ''for intval in struct.unpack('BBBBBB', buffer):if intval > 15:replacestr = '0x'else:replacestr = 'x'macaddr = ''.join([macaddr, hex(intval).replace(replacestr, '')])return macaddr.upper()if __name__ == '__main__':print 'Your mac address is %s' % get_macaddress('localhost')
IP地址:
ip = socket.gethostbyname(socket.gethostname())
这篇关于python取本地mac地址,ip地址,非ipconfig方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!