Source file
src/net/mac.go
1
2
3
4
5 package net
6
7 const hexDigit = "0123456789abcdef"
8
9
10 type HardwareAddr []byte
11
12 func (a HardwareAddr) String() string {
13 if len(a) == 0 {
14 return ""
15 }
16 buf := make([]byte, 0, len(a)*3-1)
17 for i, b := range a {
18 if i > 0 {
19 buf = append(buf, ':')
20 }
21 buf = append(buf, hexDigit[b>>4])
22 buf = append(buf, hexDigit[b&0xF])
23 }
24 return string(buf)
25 }
26
27
28
29
30
31
32
33
34
35
36
37
38
39 func ParseMAC(s string) (hw HardwareAddr, err error) {
40 if len(s) < 14 {
41 goto error
42 }
43
44 if s[2] == ':' || s[2] == '-' {
45 if (len(s)+1)%3 != 0 {
46 goto error
47 }
48 n := (len(s) + 1) / 3
49 if n != 6 && n != 8 && n != 20 {
50 goto error
51 }
52 hw = make(HardwareAddr, n)
53 for x, i := 0, 0; i < n; i++ {
54 var ok bool
55 if hw[i], ok = xtoi2(s[x:], s[2]); !ok {
56 goto error
57 }
58 x += 3
59 }
60 } else if s[4] == '.' {
61 if (len(s)+1)%5 != 0 {
62 goto error
63 }
64 n := 2 * (len(s) + 1) / 5
65 if n != 6 && n != 8 && n != 20 {
66 goto error
67 }
68 hw = make(HardwareAddr, n)
69 for x, i := 0, 0; i < n; i += 2 {
70 var ok bool
71 if hw[i], ok = xtoi2(s[x:x+2], 0); !ok {
72 goto error
73 }
74 if hw[i+1], ok = xtoi2(s[x+2:], s[4]); !ok {
75 goto error
76 }
77 x += 5
78 }
79 } else {
80 goto error
81 }
82 return hw, nil
83
84 error:
85 return nil, &AddrError{Err: "invalid MAC address", Addr: s}
86 }
87
View as plain text