I need to convert a Mac Address into an IPv6 Link
Local address.
This link-local IPv6
is infered from the NIC’s
mac address.
The conversion procedure is as given below.
take the mac address: for example 52:74:f2:b1:a8:7f
throw ff:fe in the middle: 52:74:f2:ff:fe:b1:a8:7f
reformat to IPv6 notation 5274:f2ff:feb1:a87f
convert the first octet from hexadecimal to binary: 52 -> 01010010
invert the bit at index 6 (counting from 0): 01010010 -> 01010000
convert octet back to hexadecimal: 01010000 -> 50
replace first octet with newly calculated one: 5074:f2ff:feb1:a87f
prepend the link-local prefix: fe80::5074:f2ff:feb1:a87f
This seems to be a lot of specific string manipulation and conversion between number systems.
I was looking for a utility class in Java which could help me do the same in a more efficient manner.
I see that Java has methods in InetAddress
to determine if the address in question is a link local.
The IPAddress Java library has methods to do this. Disclaimer: I am the project manager of that library.
Here is sample code using your example MAC address 52:74:f2:b1:a8:7f
String str = "52:74:f2:b1:a8:7f";
try {
MACAddress mac = new MACAddressString(str).toAddress();
IPv6Address linkLocal = mac.toLinkLocalIPv6();
System.out.println("converted " + mac + " to IPv6 link local " + linkLocal);
} catch(AddressStringException e) {
// handle invalid address string here
}
Output is:
converted 52:74:f2:b1:a8:7f to IPv6 link local fe80::5074:f2ff:feb1:a87f
More examples are in the wiki.