How to get the local mac address?
Steve Holden
steve at holdenweb.com
Thu Dec 15 03:18:09 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 ?
>
Why should you want to associate a MAC address with a socket? Each
interface has an IP address, and it's that you should be using.
> 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).
>
Indeed, and that's why most networkers probably wouldn't regard this as
a deficiency in Python's network handling but an inevitable consequence
of the diversity of architectures, utilities and drivers in today's world.
It may well be possible to write Python code that will run on all
platforms (for example, the same way as the os.path module does, by
importing the correct piece of code according to the platform), but it
would need maintenance. Since the interface MAC address is unimportant
for most network applications I guess nobody has so far thought it worth
contributing to the core.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/
More information about the Python-list
mailing list