Skip to content

Instantly share code, notes, and snippets.

@wido
Created December 21, 2016 11:56
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wido/f5e32576bb57b5cc6f934e177a37a0d3 to your computer and use it in GitHub Desktop.
Save wido/f5e32576bb57b5cc6f934e177a37a0d3 to your computer and use it in GitHub Desktop.
Python 3 48-bit MAC to EUI-64 IPv6
#!/usr/bin/env python3
import ipaddress
import re
def mac2eui64(mac, prefix=None):
'''
Convert a MAC address to a EUI64 address
or, with prefix provided, a full IPv6 address
'''
# http://tools.ietf.org/html/rfc4291#section-2.5.1
eui64 = re.sub(r'[.:-]', '', mac).lower()
eui64 = eui64[0:6] + 'fffe' + eui64[6:]
eui64 = hex(int(eui64[0:2], 16) ^ 2)[2:].zfill(2) + eui64[2:]
if prefix is None:
return ':'.join(re.findall(r'.{4}', eui64))
else:
try:
net = ipaddress.ip_network(prefix, strict=False)
euil = int('0x{0}'.format(eui64), 16)
return str(net[euil])
except: # pylint: disable=bare-except
return
print(mac2eui64(mac='06:b2:4a:00:00:9f', prefix='2001:db8:100::/64'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment