2
0

mac.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2023-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. package zerotier
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "strconv"
  18. "strings"
  19. )
  20. // MAC represents an Ethernet hardware address
  21. type MAC uint64
  22. // NewMACFromString decodes a MAC address in canonical colon-separated hex format
  23. func NewMACFromString(s string) (MAC, error) {
  24. ss := strings.Split(s, ":")
  25. if len(ss) != 6 {
  26. return MAC(0), ErrInvalidMACAddress
  27. }
  28. var m uint64
  29. for i := 0; i < 6; i++ {
  30. m <<= 8
  31. c, _ := strconv.ParseUint(ss[i], 16, 64)
  32. if c > 0xff {
  33. return MAC(0), ErrInvalidMACAddress
  34. }
  35. m |= (c & 0xff)
  36. }
  37. return MAC(m), nil
  38. }
  39. // String returns this MAC address in canonical human-readable form
  40. func (m MAC) String() string {
  41. return fmt.Sprintf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x", (m>>40)&0xff, (m>>32)&0xff, (m>>24)&0xff, (m>>16)&0xff, (m>>8)&0xff, m&0xff)
  42. }
  43. // MarshalJSON marshals this MAC as a string
  44. func (m MAC) MarshalJSON() ([]byte, error) {
  45. return []byte(m.String()), nil
  46. }
  47. // UnmarshalJSON unmarshals this MAC from a string
  48. func (m *MAC) UnmarshalJSON(j []byte) error {
  49. var s string
  50. err := json.Unmarshal(j, &s)
  51. if err != nil {
  52. return err
  53. }
  54. *m, err = NewMACFromString(s)
  55. return err
  56. }