Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MAC address generator in python

For purpose of creating bulk virtual machines, I need to create a random MAC address generator in Python. I don't know how to generate random MAC addresses.

Is the following program correct or not?

import random

# The first line is defined for specified vendor
mac = [ 0x00, 0x24, 0x81,
    random.randint(0x00, 0x7f),
    random.randint(0x00, 0xff),
    random.randint(0x00, 0xff) ]

print ':'.join(map(lambda x: "%02x" % x, mac))
like image 517
DEEPAK GEORGE Avatar asked Dec 13 '11 05:12

DEEPAK GEORGE


3 Answers

For anyone wanting to generate their own MAC addresses (a good example is for VM NICs), you probably just want this:

"02:00:00:%02x:%02x:%02x" % (random.randint(0, 255),
                             random.randint(0, 255),
                             random.randint(0, 255))

Or, if you want to do this in a unix'y shell, this works on many:

printf '02:00:00:%02X:%02X:%02X\n' $((RANDOM%256)) $((RANDOM%256)) $((RANDOM%256))

This gives you a unicast MAC address that is 100% safe to use in your environment, and isn't trampling on anyone's registered MAC address space.


More detail...

The bottom two bits of the top byte (0x02) give you a locally administered unicast address, which is probably what you want if you are hitting stackoverflow for how to generate this. :)

If the MAC address is not locally administered, it means it is supposed to be "globally unique". MAC addresses in this category are centrally registered with the IEEE, and you should have a unique OUI (Organizationally Unique Identifier) issued to you by the IEEE. See this link for the global registry of OUI values. This OUI value ends up in the first 3 bytes (or just the top 22 bits, really).

MAC addresses aren't that complicated, so you should probably also just have a look at the definition. Wikipedia has a good one.

like image 116
Russ Avatar answered Nov 14 '22 05:11

Russ


Modified from mamofish's code to Python3:

mac = '00:00:00:'
for number in range(16**6):
    hex_num = hex(number)[2:].zfill(6)
    print("{}{}{}:{}{}:{}{}".format(mac,*hex_num))

Generates mac addresses as strings from 00:00:00:00:00:00 to 00:00:00:ff:ff:ff.

like image 38
paragbaxi Avatar answered Nov 14 '22 06:11

paragbaxi


Since uniqueness is all you should care about (beyond making the address well-formed), I'd worry about the MSBs in the OUI and use a sequence in the NIC specific bytes. The distribution of the addresses is likely unimportant to your application (even though some NIC or switch implementations might use them as an input to a hash, this is likely not to be a big concern).

You may want to consider using the "locally administered" flag in the OUI to avoid a conflict with an existing device manufacturer.

Avoid pitfalls like setting the multicast bit (your example does).

like image 1
Brian Cain Avatar answered Nov 14 '22 05:11

Brian Cain