How to Extracting MAC address using Python?



Every computer needs a network interface card (NIC) to become part of a network or internet. The address assigned to this card is known as the MAC address. The value of the MAC address is unique for every NIC. It also applies to other devices that can connect to LAN or internet like printers and routers.

To find the MAC address we use one of the following methods.

Using uuid.getnode()

The uuid module has a getnode() function which gives us the MAC address in a hexadecimal format.

Example

import uuid
print(hex(uuid.getnode()))

Output

Running the above code gives us the following result −

0xfee14ef7a96

Using getnode() + format()

We format the result for better readability in this method. Here we join elements of each node after 2 digits and represent them by separating them with colon.

Example

 Live Demo

import uuid
print ("Formatted MAC address : ")
print (':'.join(['{:02x}'.format((uuid.getnode() >> elements) & 0xff)
for elements in range(0,2*6,2)][::-1]))

Output

Running the above code gives us the following result −

Formatted MAC address :
de:7a:ea:a9:a5:96

Using getnode() + findall() + re()

We use the same approach as the previous one but we use regular expression module (re) to format the result. This makes the result much less complex.

Example

import re,uuid
print ("Formatted MAC address : ")
print (':'.join(re.findall('..', '%012x' % uuid.getnode())))

Output

Running the above code gives us the following result −

Formatted MAC address:
0f:ee:14:ef:7a:96
raja
Published on 17-Oct-2019 16:07:05
Advertisements