Advertisement
DeaD_EyE

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

Oct 19th, 2022 (edited)
1,184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.45 KB | None | 0 0
  1. from operator import itemgetter
  2.  
  3.  
  4. def get_mac(interface: str) -> str:
  5.     """
  6.    Get MAC Address of network interface.
  7.    """
  8.     try:
  9.         with open(f"/sys/class/net/{interface}/address") as fd:
  10.             return fd.read().strip()
  11.     except FileNotFoundError as err:
  12.         raise ValueError(f"Interface '{interface}' not found.") from None
  13.  
  14.  
  15. def get_ips(interface: str) -> list[str]:
  16.     with open("/proc/net/route") as fd:
  17.         lines = fd.readlines()
  18.  
  19.     select = itemgetter(1, 7)
  20.     to_hex = lambda x: int(x, 16)
  21.     addrs = []
  22.     for line in lines:
  23.         if line.startswith(interface):
  24.             data = line.split()
  25.  
  26.             if not all(map(to_hex, select(data))):
  27.                 continue
  28.  
  29.             value = int(data[1], 16)
  30.             ip_blocks = [str((value >> shift) & 0xFF) for shift in range(0, 32, 8)]
  31.             addrs.append(".".join(ip_blocks))
  32.  
  33.     return addrs
  34.  
  35.  
  36. def get_ips6(interface: str) -> list[str]:
  37.     with open("/proc/net/if_inet6") as fd:
  38.         lines = fd.readlines()
  39.  
  40.     addrs = []
  41.     for line in lines:
  42.         ip6, *_, name = line.split()
  43.         if name != interface:
  44.             continue
  45.  
  46.         ip6 = int(ip6, 16)
  47.         bit_shifter = range(112, -1, -16)
  48.         ip_blocks = [f"{(ip6 >> shift) & 0xFFFF:04x}" for shift in bit_shifter]
  49.         addrs.append(":".join(ip_blocks))
  50.  
  51.     return addrs
  52.  
  53.  
  54. mac, ips4, ips6 = get_mac("wlan0"), get_ips("wlan0"), get_ips6("wlan0")
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement