You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python网络:如何将psutil获取的MAC地址添加到网卡列表中

How to Add MAC Addresses from psutil.net_if_addrs() to Your List

Hey there! First off, kudos for working with pmav99's script—big props to them for the solid starting point. Let's sort out how to pull those MAC addresses into your list, even though the address key is shared with IP addresses.

The secret here is that every entry from psutil.net_if_addrs() is a snicaddr object, not just a raw string. This object has a family attribute that lets you distinguish MAC addresses from IPs. MACs are always linked to the psutil.AF_LINK family (this works cross-platform, so no fuss with Windows vs. Linux differences).

Here's a hands-on example to extract and add MAC addresses to your list:

import psutil

# Initialize a list to store your MAC addresses (customize as needed)
mac_list = []

# Loop through all network interfaces
for iface_name, iface_addrs in psutil.net_if_addrs().items():
    for addr in iface_addrs:
        # Check if this entry is a MAC address
        if addr.family == psutil.AF_LINK:
            # Add the MAC to your list—you can include the interface name too for clarity
            mac_list.append(f"{iface_name}: {addr.address}")
            # If you just want the raw MAC string, use: mac_list.append(addr.address)

# Verify your collected MACs
print("Collected MAC Addresses:")
for mac in mac_list:
    print(mac)

Quick breakdown of the key bits:

  • psutil.net_if_addrs() gives you a dictionary where keys are interface names (like eth0 or Wi-Fi) and values are lists of snicaddr objects.
  • Each snicaddr has properties: family (tells you the address type), address (the actual address string), netmask, and more.
  • By checking addr.family == psutil.AF_LINK, we filter out IPv4 (psutil.AF_INET) and IPv6 (psutil.AF_INET6) addresses, leaving only MACs to add to your list.

If you want to merge this with pmav99's existing script (say, collecting both IPs and MACs), just extend the loop with conditionals for each address family—easy to slot into your current workflow.

Hope this gets you sorted out! 😊

内容的提问来源于stack exchange,提问作者Park Yo Jin

火山引擎 最新活动