How to get the local mac address?

bonono at gmail.com bonono at gmail.com
Wed Dec 14 22:50:52 EST 2005


Daniel Crespo wrote:
> Hi, I tried:
>
> import ctypes
> import socket
> import struct
>
> def get_macaddress(host):
>     """ Returns the MAC address of a network host, requires >= WIN2K.
> """
>
>     # Check for api availability
>     try:
>         SendARP = ctypes.windll.Iphlpapi.SendARP
>     except:
>         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 Exception
>     except:
>         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')
>
> It works perfect under W2K and above. But I would like to run it on
> Win98 too. Any help?
>
Sorry that I can't help you in any way but have a question myself.  Is
there an OS independent way to get this thing(regardless of how to
format it) in Python ? I know this may not matter if all you want is
Windows but there is just another thread talking about one should write
programs that is OS independent.

Is this a problem of the network library of python ?




More information about the Python-list mailing list