Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/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)
- >>> mac_value = 0x237702d2ff9b
- >>> format(mac_value, '012x')
- '237702d2ff9b'
- >>> format(42, '012x')
- '00000000002a'
- def mac_to_ipv6_linklocal(mac):
- # Remove the most common delimiters; dots, dashes, etc.
- mac_value = int(mac.translate(None, ' .:-'), 16)
- # Split out the bytes that slot into the IPv6 address
- # XOR the most significant byte with 0x02, inverting the
- # Universal / Local bit
- high2 = mac_value >> 32 & 0xffff ^ 0x0200
- high1 = mac_value >> 24 & 0xff
- low1 = mac_value >> 16 & 0xff
- low2 = mac_value & 0xffff
- return 'fe80::{:04x}:{:02x}ff:fe{:02x}:{:04x}'.format(
- high2, high1, low1, low2)
Add Comment
Please, Sign In to add comment