hii readers,
Introduction
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.
Example Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import socket 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 s.bind((interface,p))
# extract mac address mac = hexlify(s.getsockname()[4])
# close socket s.close()
#return value return mac |
Explanation
- 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