DeaD_EyE icon

get mac and ip from /sys/class/net/... and /proc/net/...

DeaD_EyE | PRO | 10/19/22 10:30:34 AM UTC (Edited) | 0 ⭐ | 1653 👁️ | Never ⏰ | []
Python |

1.45 KB

|

None

|

0 👍

/

0 👎

from operator import itemgetter
 
 
def get_mac(interface: str) -> str:
    """
    Get MAC Address of network interface.
    """
    try:
        with open(f"/sys/class/net/{interface}/address") as fd:
            return fd.read().strip()
    except FileNotFoundError as err:
        raise ValueError(f"Interface '{interface}' not found.") from None
 
 
def get_ips(interface: str) -> list[str]:
    with open("/proc/net/route") as fd:
        lines = fd.readlines()
 
    select = itemgetter(1, 7)
    to_hex = lambda x: int(x, 16)
    addrs = []
    for line in lines:
        if line.startswith(interface):
            data = line.split()
 
            if not all(map(to_hex, select(data))):
                continue
 
            value = int(data[1], 16)
            ip_blocks = [str((value >> shift) & 0xFF) for shift in range(0, 32, 8)]
            addrs.append(".".join(ip_blocks))
 
    return addrs
 
 
def get_ips6(interface: str) -> list[str]:
    with open("/proc/net/if_inet6") as fd:
        lines = fd.readlines()
 
    addrs = []
    for line in lines:
        ip6, *_, name = line.split()
        if name != interface:
            continue
 
        ip6 = int(ip6, 16)
        bit_shifter = range(112, -1, -16)
        ip_blocks = [f"{(ip6 >> shift) & 0xFFFF:04x}" for shift in bit_shifter]
        addrs.append(":".join(ip_blocks))
 
    return addrs
 
 
mac, ips4, ips6 = get_mac("wlan0"), get_ips("wlan0"), get_ips6("wlan0")
 

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎