Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How can I convert a Mac address into an ipv6 Link-Local address?

you have to add fe80:: at the start and insert ff:fe in the middle

furthermore all leading zeros must be stripped

share|improve this question
    
You also have to flip the universal/local bit. –  Michael Hampton Jun 14 '13 at 0:08
add comment

2 Answers

up vote 3 down vote accepted

You can use IFS to split the MAC address into 6 colon-separated groups and assemble them. You'll also need to flip the 7th most significant bit (thanks bahamat), i.e. bit 1 of the first byte.

mac_to_ipv6 () {
  IFS=':'; set $1; unset IFS
  ipv6_address="fe80::$(printf %02x $((0x$1 ^ 2)))$2:${3}ff:fe$4:$5$6"
}

You can use the prefix and suffix stripping constructs ${VAR#PREFIX} and ${VAR%SUFFIX} to cut the MAC address into pieces.

mac_to_ipv6 () {
  mac=$1
  ipv6_address=fe80::$(printf %02x $((0x${mac%%:*} ^ 2)))
  mac=${mac#*:}
  ipv6_address=$ipv6_address${mac%:*:*:*}ff:fe
  mac=${mac#*:*:}
  ipv6_address=$ipv6_address${mac%:*}${mac##*:}
}

You can use the substring construct (bash only, not sh).

mac_to_ipv6 () {
  local mac=$1 byte0
  printf %02x -v byte0 $((0x${mac:0:2} ^ 2))
  ipv6_address="fe80::$byte0${mac:3:5}ff:fe${mac:9:5}${mac:15:2}"
}
share|improve this answer
    
This doesn't work because link-local addresses have the 7th bit flipped high. –  bahamat Jun 14 '13 at 5:35
    
@bahamat Fixed, thanks. –  Gilles Jun 14 '13 at 10:23
add comment

Taking Gilles' explanation, but correctly flipping the 7th bit as per IPv6 spec:

#!/bin/bash

IFS=':'; set $1; unset IFS
printf "fe80::%x%x:%x:%x:%x\n" 0x$(( 0x${1} ^ 0x02 )) 0x${2} 0x${3}ff 0xfe${4} 0x${5}${6}

Example of bit-flipping:

$ mac_to_ipv6 00:00:00:00:00:00
fe80::200:00ff:fe00:0000
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.