def get_interface_mac(sock: socket.socket, ifname: str) -> str:
"""Obtain a network interface's MAC address, as a string."""
ifreq = struct.pack(b'256s', ifname.encode('utf-8')[:15])
try:
info = fcntl.ioctl(sock.fileno(), SIOCGIFHWADDR, ifreq)
except OSError as e:
if e.errno is not None and e.errno == errno.ENODEV:
raise InterfaceNotFound(
"Interface not found: '%s'." % ifname)
else:
raise MACAddressNotAvailable(
"Failed to get MAC address for '%s': %s." % (
ifname, strerror(e.errno)))
else:
# Of course we're sure these are the correct indexes into the `ifreq`.
# Also, your lack of faith is disturbing.
mac = ''.join('%02x:' % char for char in info[18:24])[:-1]
return mac
评论列表
文章目录