美文网首页
Python_获取当前终端可用网卡MAC及IP

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

作者: 古佛青灯度流年 | 来源:发表于2018-07-27 17:29 被阅读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

相关文章

网友评论

      本文标题:Python_获取当前终端可用网卡MAC及IP

      本文链接:https://www.haomeiwen.com/subject/xqmgmftx.html