Python script to generate a random MAC address
This script generates a completely random MAC address without requiring any external libraries. It ensures that the MAC address is locally administered and unicast.
#!/usr/bin/env python3
import random
def generate_mac():
# First byte: ensure locally administered and unicast
first = random.randint(0x02, 0xfe) & 0xfe # Set bit 1, clear bit 0
# Generate remaining 5 bytes
remainders = [random.randint(0x00, 0xff) for _ in range(5)]
# Combine all bytes and format as MAC
mac_bytes = [first] + remainders
mac_addr = ':'.join([f'{b:02x}' for b in mac_bytes])
return mac_addr
if __name__ == '__main__':
print(f"Random MAC: {generate_mac()}")
How to use
- Copy the script to a file, e.g.,
generate_mac.py
. - Run the script with Python 3:
python3 generate_mac.py
.
Example output
Random MAC: de:bb:9c:15:6d:24
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow