Skip to content

Instantly share code, notes, and snippets.

Created September 17, 2013 07:44
What would you like to do?
generate random mac address for xen or qemu
#!/usr/bin/env python
import sys
import random
# this function is directly from xend/server/ and is thus
# available under the LGPL,
# Copyright 2004, 2005 Mike Wray <>
# Copyright 2005 XenSource Ltd
def randomMAC(type="xen"):
"""Generate a random MAC address.
00-16-3E allocated to xensource
52-54-00 used by qemu/kvm
The OUI list is available at
The remaining 3 fields are random, with the first bit of the first
random field set 0.
>>> randomMAC().startswith("00:16:3E")
>>> randomMAC("foobar").startswith("00:16:3E")
>>> randomMAC("xen").startswith("00:16:3E")
>>> randomMAC("qemu").startswith("52:54:00")
@return: MAC address string
ouis = { 'xen': [ 0x00, 0x16, 0x3E ], 'qemu': [ 0x52, 0x54, 0x00 ] }
oui = ouis[type]
except KeyError:
oui = ouis['xen']
mac = oui + [
random.randint(0x00, 0xff),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff)]
return ':'.join(map(lambda x: "%02x" % x, mac))
if __name__ == "__main__":
print randomMAC("xen" if len(sys.argv) < 2 else sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment