代码片段:Python 中使用 psutil 库获取本机网卡及IP地址,使用 ipaddress 库判定地址类型


import socket
import psutil
import ipaddress


def getInterface(): # 获取网卡信息
    net_if_addrs = psutil.net_if_addrs()
    interfaces = []
    for k in net_if_addrs:
        # a new net_interface
        netif = {'name': k}
        for v in net_if_addrs[k]:   #snicaddr(family=<AddressFamily.AF_LINK: -1>, address='AA-BB-', netmask=None, broadcast=None, ptp=None)
            # check address
            try:
                if v[0] == psutil.AF_LINK:  #MAC
                    netif['mac'] = v[1]
                elif v[0] == socket.AddressFamily.AF_INET:  #IPv4
                    v4 = ipaddress.IPv4Address(v[1])
                    if v4.is_global:
                        if "ipv4" not in netif:
                            netif["ipv4"] = []
                        netif["ipv4"].append({
                            'ip': v[1],
                            'type': 'global',
                        })
                    elif v4.is_private:
                        if v4.is_link_local or v4.is_loopback or v4.is_reserved:
                            continue
                        if "ipv4" not in netif:
                            netif["ipv4"] = []
                        netif["ipv4"].append({
                            'ip': v[1],
                            'type': 'private',
                        })
                elif v[0] == socket.AddressFamily.AF_INET6: #IPv6
                    v6 = ipaddress.IPv6Address(v[1])
                    if v6.is_global:
                        if "ipv6" not in netif:
                            netif["ipv6"] = []
                        netif["ipv6"].append({
                            'ip': v[1],
                            'type': 'global',
                        })
            except Exception:
                pass
        if "ipv4" in netif or "ipv6" in netif:
            interfaces.append(netif)
    return interfaces

def getIPs():   # 从网卡信息中读取IP
    interfaces = getInterface()
    IPs={"global":[],"private":[]}
    for i in interfaces:
        if "ipv4" in i:
            for v4 in i["ipv4"]:
                if v4["type"] == "global":
                    IPs["global"].append({
                        "ip": v4["ip"],
                        "name": i["name"],
                    })
                else:
                    IPs["private"].append({
                        "ip": v4["ip"],
                        "name": i["name"],
                    })
        if "ipv6" in i:
            for v6 in i["ipv6"]:
                if v6["type"] == "global":
                    IPs["global"].append({
                        "ip": v6["ip"],
                        "name": i["name"],
                    })
    return IPs

def getGlobalIPs(): # 获取全局IP地址
    IPs = getIPs()['global']
    globalIPs = [i['ip'] for i in IPs]
    return globalIPs

print(getInterface())
print(getIPs())
print(getGlobalIPs())

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Back to Top