python 获取mac地址

方法一:使用socket库

使用了socket库中的ioctl函数和fcntl模块来获取MAC地址

import socket
import fcntl
import struct
 
def get_mac_address():
    interface = 'eth0'  # 替换为你的网络接口名称,例如eth0或en0
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    mac = fcntl.ioctl(sock.fileno(), 0x8927, struct.pack('256s', interface[:15].encode('utf-8')))
    mac = ''.join(['{:02X}'.format(b) for b in mac[18:24]])
    return mac
方法二:使用uuid库

使用了uuid库的getnode函数来获取MAC地址

import uuid
 
def get_mac_address():
    mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
    return mac
方法三:使用psutil库

使用了psutil库来获取网卡信息,并从中提取MAC地址

import psutil
 
def get_mac_address():
    interfaces = psutil.net_if_addrs()
    for interface_name, addresses in interfaces.items():
        for address in addresses:
            if address.family == psutil.AF_LINK:
                mac = address.address.replace(':', '')
                return mac

作者:Take_a_chestnut

物联沃分享整理
物联沃-IOTWORD物联网 » python 获取mac地址

发表回复