python 物理地址,python-在Windows中正确获取MAC地址

在Windows 7和Python 2.6环境下,通过wmimodule和uuidmodule获取MAC地址的方法进行了探讨。当没有互联网连接时,wmimodule可能会出现问题。文章提供了将48位MAC地址数值转换为冒号分隔格式的三种方法,并强调了正确获取MAC地址的重要性。
摘要由CSDN通过智能技术生成

I'm using Windows 7 and Python 2.6. I would like to get the MAC address of my network interface.

I've tried using the wmi module:

def get_mac_address():

c = wmi.WMI ()

for interface in c.Win32_NetworkAdapterConfiguration (IPEnabled=1):

return interface.MACAddress

However, experienced issues when executed without internet connectivity.

I've tried using the uuid module:

from uuid import getnode

print getnode()

However, return value is a 48 byte representation of the MAC address

66610803803052

1) How should I convert the given number to ff:ff:ff:ff:ff:ff format?

2) Is there a better way to get the MAC address?

解决方案

This works:

>>> address = 1234567890

>>> h = iter(hex(address)[2:].zfill(12))

>>> ":".join(i + next(h) for i in h)

'00:00:49:96:02:d2'

Or:

>>> "".join(c + ":" if i % 2 else c for i, c in enumerate(hex(address)[2:].zfill(12)))[:-1]

'00:00:49:96:02:d2'

Or:

>>> h = hex(address)[2:].zfill(12)

>>> ":".join(i + j for i, j in zip(h[::2], h[1::2]))

'00:00:49:96:02:d2'

You first convert the number to hex, pad it to 12 chars, and then convert it to a series of two char strings, and then join them with colons. However, this depends on the accuracy of your MAC-finding method.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值