Extracting MAC address using Python

PythonProgrammingServer Side Programming

We know that the MAC address is a hardware address which means it is unique for the network card installed on our PC. It is always unique that means no two devices on a local network could have the same MAC addresses.

The main purpose of MAC address is to provide a unique hardware address or physical address for every node on a local area network (LAN) or other networks. A node means a point at which a computer or other device (e.g. a printer or router) will remain connected to the network.

Method1

Using uuid.getnode()

In this example getnode() can be used to extract the MAC address of the computer. This function is defined in uuid module.

Example code

Live Demo

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

Output

0x242ac110002L

Method2

Using getnode() + format() [ This is for better formatting ]

Example code

import uuid
# after each 2 digits, join elements of getnode().
print ("The formatted MAC address is : ", end="")
print (':'.join(['{:02x}'.format((uuid.getnode() >> elements) & 0xff)
for elements in range(0,2*6,2)][::-1]))

Output

The formatted MAC address is : 3e:f8:e2:8b:2c:b3

Method3

Using getnode() + findall() + re()[ This is for reducing complexity]

Example code

import re, uuid
# after each 2 digits, join elements of getnode().
# using regex expression
print ("The MAC address in expressed in formatted and less complex way : ", end="")
print (':'.join(re.findall('..', '%012x' % uuid.getnode())))

Output

The MAC address in expressed in formatted and less complex way : 18:5e:0f:d4:f8:b3
raja
Published on 23-Nov-2018 16:41:10
Advertisements