MAC address generator in python

后端 未结 4 1462
时光说笑
时光说笑 2021-02-15 16:03

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 foll

4条回答
  •  借酒劲吻你
    2021-02-15 16:32

    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.

提交回复
热议问题