Random MAC Address Generator in Python
In this article, we will learn about how to generate a random MAC address using Python. First of all, let us know what is the MAC Address.
For us to communicate with friends and relatives we have our house address. Similarly, computers have MAC addresses to communicate with other devices in the network. These addresses are unique for each device. It is a 48-bit address embedded in a computer when manufacturing it.
First of all, for this program to work we need Python 3.2 or greater, so make sure to upgrade python. Simultaneously need to install a module called Randmac. For installing it open Command Prompt and type the following command to install. Make sure that your computer is connected to the internet.
#For Windows users pip install randmac #For Mac users pip install randmac #For Linux users sudo pip install randmac
Random MAC addresses are of 2 types:
- 6 – byte MAC address
- 12 – byte MAC address
Generating 6 – byte MAC Address in Python
Randmac module consists of a class called RandMac which generates random MAC addresses. So we should import Randmac module in our code.
from randmac import RandMac example_mac = "00-00-00-00-00-00" generated_mac = RandMac(example_mac) print("Generated 6-byte mac address: ",generated_mac)
Generated 6-byte mac address: '00-00-00-ac-63-17'
NOTE:- Output changes every time you run the program because it is similar to the random function.
We are giving an example MAC address to the example_mac variable. RandMac class takes this variable as a parameter and generates a new 6- byte MAC address and saves it in another variable called generated_mac, and we are printing it. Hence it is 6-byte address output contains the first 6 digits 0’s as a result.
MAC also supports the following formats:
Generating 12 – byte MAC Address:
Finally, 12 byte MAC address generation is similar to 6-byte but we are sending true parameter to RandMac class. Here RandMac class takes example_mac address and True value as class parameters simultaneously.
See the Python code below that will generate random 12 byte MAC address
from randmac import RandMac example_mac = "0000.0000.0000" generated_mac = RandMac(example_mac, True) print("Generated 12-byte mac address:",generated_mac)
Generated 12-byte mac address: 'ca92.885b.d863'
Also, read: C++ program to get MAC address of a device