In this post, I am going to tell you about how we can easily get the address of our interface using python socket module. Actually, To retrieve the mac address of our card here we going to use python socket module sock name function.
Sock name function returns socket information as a tuple. so, to get the mac address of your interface card, first, we need to create a dummy socket object and then, bind it with the specific interface. basically, specific interface means the interface whose address you want to find.
from binascii import hexlify
# get mac address
def get_mac(interface, p=0):
# create dummy socket
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
# bind it with interface name
# extract mac address
mac = hexlify(s.getsockname())
# close socket
- line 8, To create a dummy socket object.
- line 11, Bind socket with interface card.
- line 14, extract mac address from tuple
- line 17, close socket