How to get the local mac address?
Frank Millman
frank at chagford.com
Thu Dec 15 03:20:56 EST 2005
bonono at gmail.com wrote:
> Frank Millman wrote:
> > bonono at gmail.com wrote:
> > > 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 ?
> >
> > This is not a generic solution, but it works for me on Linux and
> > Windows
> >
> > def getMacAddress():
> > if sys.platform == 'win32':
> > for line in os.popen("ipconfig /all"):
> > if line.lstrip().startswith('Physical Address'):
> > mac = line.split(':')[1].strip().replace('-',':')
> > break
> > else:
> > for line in os.popen("/sbin/ifconfig"):
> > if line.find('Ether') > -1:
> > mac = line.split()[4]
> > break
> > return mac
> >
> Thanks, but how can I associate the result to the socket, assuming that
> is the reason for wanting to get at the MAC ?
>
> I see that some *nix implementation use fcntl/ioctl to read this info
> out of the file handle of a socket but these modules don't exist on
> Windows(may be some other platform as well).
As you can see, this is a quick and dirty solution.
I am sure you can hack at it some more, bring up the associated ip
address, and compare it with socket.gethostbyaddr() or similar.
I don't know of a more correct solution - maybe someone else can advise
better.
BTW I recall a response some time ago warning that you cannot rely on a
mac address, as they can be modified. Depending on your intended use,
this may or may not be important.
Sorry I cannot be of more help
Frank
More information about the Python-list
mailing list