Skip to content

Instantly share code, notes, and snippets.

@viz3
Created September 17, 2013 07:44
Show Gist options
  • Save viz3/6591201 to your computer and use it in GitHub Desktop.
Save viz3/6591201 to your computer and use it in GitHub Desktop.
generate random mac address for xen or qemu
#!/usr/bin/env python
import sys
import random
# this function is directly from xend/server/netif.py and is thus
# available under the LGPL,
# Copyright 2004, 2005 Mike Wray <mike.wray@hp.com>
# 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 http://standards.ieee.org/regauth/oui/oui.txt.
The remaining 3 fields are random, with the first bit of the first
random field set 0.
>>> randomMAC().startswith("00:16:3E")
True
>>> randomMAC("foobar").startswith("00:16:3E")
True
>>> randomMAC("xen").startswith("00:16:3E")
True
>>> randomMAC("qemu").startswith("52:54:00")
True
@return: MAC address string
"""
ouis = { 'xen': [ 0x00, 0x16, 0x3E ], 'qemu': [ 0x52, 0x54, 0x00 ] }
try:
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