Created
March 31, 2021 19:53
-
-
Save 0xef53/cb1c5d7594683982ba41d303ac03e9a0 to your computer and use it in GitHub Desktop.
MAC address to IPv6 link-local address
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"net" | |
) | |
func mac2ip(s string) (net.IP, error) { | |
mac, err := net.ParseMAC(s) | |
if err != nil { | |
return nil, err | |
} | |
// Invert the bit at the index 6 (counting from 0) | |
mac[0] ^= (1 << (2 - 1)) | |
ip := []byte{ | |
0xfe, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // prepend with fe80:: | |
mac[0], mac[1], mac[2], 0xff, 0xfe, mac[3], mac[4], mac[5], // insert ff:fe in the middle | |
} | |
return ip, nil | |
} | |
func main() { | |
ip, err := mac2ip("02:42:18:35:e7:5a") | |
if err != nil { | |
log.Fatalln(err) | |
} | |
fmt.Println(ip) // prints fe80::42:18ff:fe35:e75a | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment