hwaddr.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2016 CNI authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package hwaddr
  15. import (
  16. "fmt"
  17. "net"
  18. )
  19. const (
  20. ipRelevantByteLen = 4
  21. PrivateMACPrefixString = "0a:58"
  22. )
  23. var (
  24. // private mac prefix safe to use
  25. PrivateMACPrefix = []byte{0x0a, 0x58}
  26. )
  27. type SupportIp4OnlyErr struct{ msg string }
  28. func (e SupportIp4OnlyErr) Error() string { return e.msg }
  29. type MacParseErr struct{ msg string }
  30. func (e MacParseErr) Error() string { return e.msg }
  31. type InvalidPrefixLengthErr struct{ msg string }
  32. func (e InvalidPrefixLengthErr) Error() string { return e.msg }
  33. // GenerateHardwareAddr4 generates 48 bit virtual mac addresses based on the IP4 input.
  34. func GenerateHardwareAddr4(ip net.IP, prefix []byte) (net.HardwareAddr, error) {
  35. switch {
  36. case ip.To4() == nil:
  37. return nil, SupportIp4OnlyErr{msg: "GenerateHardwareAddr4 only supports valid IPv4 address as input"}
  38. case len(prefix) != len(PrivateMACPrefix):
  39. return nil, InvalidPrefixLengthErr{msg: fmt.Sprintf(
  40. "Prefix has length %d instead of %d", len(prefix), len(PrivateMACPrefix)),
  41. }
  42. }
  43. ipByteLen := len(ip)
  44. return (net.HardwareAddr)(
  45. append(
  46. prefix,
  47. ip[ipByteLen-ipRelevantByteLen:ipByteLen]...),
  48. ), nil
  49. }