Python_获取当前终端可用网卡MAC及IP

def getIP():
    import socket
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    ip = (s.getsockname()[0])
    s.close()
    return ip

def get_netcard():
from psutil import net_if_addrs
    name = ip = mac = ''
    info = net_if_addrs()
    for k, v in info.items():
        for item in range(0, len(v)):
            if v[item][0] == 2 and getIP() in v[item][1]:
                name = k
                ip = v[item][1]
                break
    if name:
        data = info[name]
        for i in data:
            if '-' in i[1] or ':' in i[1]:
                if len(i[1])==17:
                    mac = str(i[1]).replace('-','').replace(':','')
                    break

    info = {'name': name, 'ip': ip, 'mac': mac}
    log.debug('当前终端INFO:{}'.format(info))
    return info

你可能感兴趣的:(Python_获取当前终端可用网卡MAC及IP)