One of the ways I learn a new scripting language is to implement a subroutine to convert a network MAC addr into the IPv6 link-local address, as described in RFC 4862. So here is a quick few lines.
My question to you is:
- can this code be shrunk any more?
- is there a more pythonic way of doing this?
- is there anything non-optimal?
- is the code future proof to 3.4 python?
Especially with casting a string to an int, and finally back to hex, seems overly weird.
Also, I did recently discover some IP related factory functions, but so far I've not discovered any builtin way of doing this. I'm using python 2.7, but my Linux distro is soon to switch to 3.x.
#!/usr/bin/python
"""
convert mac addr to ipv6 link local (rfc 4862)
"""
# the mac should become: fe80::2177:02ff:fed2:ff9b
mac='23:77:02:d2:ff:9b'
def mac_to_ipv6_linklocal(mac):
# remove the most common macaddr delimiters, dots, dashes, etc.
# cast the hex string to an base-16 int for math safety.
# use xor of 02 on the 2nd most significant hex char.
# Remove/slice the '0x' off the begining from using hex().
m = hex(int(mac.translate(None,' .:-'),16)^0x020000000000)[2:]
return 'fe80::%s:%sff:fe%s:%s' %(m[:4],m[4:6],m[6:8],m[8:12])
print mac_to_ipv6_linklocal(mac)