Skip to content

Instantly share code, notes, and snippets.

@JayZar21
Forked from zhenyi2697/get_mac_address.py
Last active April 20, 2020 13:39
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JayZar21/6f3fd031430d865d208c29ba55ce7ccb to your computer and use it in GitHub Desktop.
Save JayZar21/6f3fd031430d865d208c29ba55ce7ccb to your computer and use it in GitHub Desktop.
Python: get mac address of a interface
# Python 2:
import socket
import fcntl
import struct
def getHwAddr(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15]))
return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]
# Python 3:
import fcntl
import socket
import struct
import binascii
def get_hw_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', bytes(ifname[:15], 'utf-8')))
return ''.join(l + ':' * (n % 2 == 1) for n, l in enumerate(binascii.hexlify(info[18:24]).decode('utf-8')))[:-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment