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

2018-07-27  本文已影响120人  古佛青灯度流年
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
上一篇 下一篇

猜你喜欢

热点阅读