mac.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // MAC address manipulations
  5. package net
  6. import "errors"
  7. const hexDigit = "0123456789abcdef"
  8. // A HardwareAddr represents a physical hardware address.
  9. type HardwareAddr []byte
  10. func (a HardwareAddr) String() string {
  11. if len(a) == 0 {
  12. return ""
  13. }
  14. buf := make([]byte, 0, len(a)*3-1)
  15. for i, b := range a {
  16. if i > 0 {
  17. buf = append(buf, ':')
  18. }
  19. buf = append(buf, hexDigit[b>>4])
  20. buf = append(buf, hexDigit[b&0xF])
  21. }
  22. return string(buf)
  23. }
  24. // ParseMAC parses s as an IEEE 802 MAC-48, EUI-48, or EUI-64 using one of the
  25. // following formats:
  26. // 01:23:45:67:89:ab
  27. // 01:23:45:67:89:ab:cd:ef
  28. // 01-23-45-67-89-ab
  29. // 01-23-45-67-89-ab-cd-ef
  30. // 0123.4567.89ab
  31. // 0123.4567.89ab.cdef
  32. func ParseMAC(s string) (hw HardwareAddr, err error) {
  33. if len(s) < 14 {
  34. goto error
  35. }
  36. if s[2] == ':' || s[2] == '-' {
  37. if (len(s)+1)%3 != 0 {
  38. goto error
  39. }
  40. n := (len(s) + 1) / 3
  41. if n != 6 && n != 8 {
  42. goto error
  43. }
  44. hw = make(HardwareAddr, n)
  45. for x, i := 0, 0; i < n; i++ {
  46. var ok bool
  47. if hw[i], ok = xtoi2(s[x:], s[2]); !ok {
  48. goto error
  49. }
  50. x += 3
  51. }
  52. } else if s[4] == '.' {
  53. if (len(s)+1)%5 != 0 {
  54. goto error
  55. }
  56. n := 2 * (len(s) + 1) / 5
  57. if n != 6 && n != 8 {
  58. goto error
  59. }
  60. hw = make(HardwareAddr, n)
  61. for x, i := 0, 0; i < n; i += 2 {
  62. var ok bool
  63. if hw[i], ok = xtoi2(s[x:x+2], 0); !ok {
  64. goto error
  65. }
  66. if hw[i+1], ok = xtoi2(s[x+2:], s[4]); !ok {
  67. goto error
  68. }
  69. x += 5
  70. }
  71. } else {
  72. goto error
  73. }
  74. return hw, nil
  75. error:
  76. return nil, errors.New("invalid MAC address: " + s)
  77. }