Guest User

Untitled

a guest
Jan 23rd, 2018
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. #!/usr/bin/python
  2. """
  3. convert mac addr to ipv6 link local (rfc 4862)
  4. """
  5.  
  6. # the mac should become: fe80::2177:02ff:fed2:ff9b
  7. mac='23:77:02:d2:ff:9b'
  8.  
  9. def mac_to_ipv6_linklocal(mac):
  10.  
  11. # remove the most common macaddr delimiters, dots, dashes, etc.
  12. # cast the hex string to an base-16 int for math safety.
  13. # use xor of 02 on the 2nd most significant hex char.
  14. # Remove/slice the '0x' off the begining from using hex().
  15.  
  16. m = hex(int(mac.translate(None,' .:-'),16)^0x020000000000)[2:]
  17. return 'fe80::%s:%sff:fe%s:%s' %(m[:4],m[4:6],m[6:8],m[8:12])
  18.  
  19.  
  20. print mac_to_ipv6_linklocal(mac)
  21.  
  22. >>> mac_value = 0x237702d2ff9b
  23. >>> format(mac_value, '012x')
  24. '237702d2ff9b'
  25. >>> format(42, '012x')
  26. '00000000002a'
  27.  
  28. def mac_to_ipv6_linklocal(mac):
  29. # Remove the most common delimiters; dots, dashes, etc.
  30. mac_value = int(mac.translate(None, ' .:-'), 16)
  31.  
  32. # Split out the bytes that slot into the IPv6 address
  33. # XOR the most significant byte with 0x02, inverting the
  34. # Universal / Local bit
  35. high2 = mac_value >> 32 & 0xffff ^ 0x0200
  36. high1 = mac_value >> 24 & 0xff
  37. low1 = mac_value >> 16 & 0xff
  38. low2 = mac_value & 0xffff
  39.  
  40. return 'fe80::{:04x}:{:02x}ff:fe{:02x}:{:04x}'.format(
  41. high2, high1, low1, low2)
Add Comment
Please, Sign In to add comment