Debian Codegraph @

src/net/mac.go

raw
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
5 package net
6
7 const hexDigit = "0123456789abcdef"
8
9 // A HardwareAddr represents a physical hardware address.
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 // ParseMAC parses s as an IEEE 802 MAC-48, EUI-48, EUI-64, or a 20-octet
28 // IP over InfiniBand link-layer address using one of the following formats:
29 //
30 // 00:00:5e:00:53:01
31 // 02:00:5e:10:00:00:00:01
32 // 00:00:00:00:fe:80:00:00:00:00:00:00:02:00:5e:10:00:00:00:01
33 // 00-00-5e-00-53-01
34 // 02-00-5e-10-00-00-00-01
35 // 00-00-00-00-fe-80-00-00-00-00-00-00-02-00-5e-10-00-00-00-01
36 // 0000.5e00.5301
37 // 0200.5e10.0000.0001
38 // 0000.0000.fe80.0000.0000.0000.0200.5e10.0000.0001
39 // 00005e005301
40 func ParseMAC(s string) (hw HardwareAddr, err error) {
41 if len(s) < 12 {
42 goto error
43 }
44
45 if s[2] == ':' || s[2] == '-' {
46 if (len(s)+1)%3 != 0 {
47 goto error
48 }
49 n := (len(s) + 1) / 3
50 if n != 6 && n != 8 && n != 20 {
51 goto error
52 }
53 hw = make(HardwareAddr, n)
54 for x, i := 0, 0; i < n; i++ {
55 var ok bool
56 if hw[i], ok = xtoi2(s[x:], s[2]); !ok {
57 goto error
58 }
59 x += 3
60 }
61 } else if s[4] == '.' {
62 if (len(s)+1)%5 != 0 {
63 goto error
64 }
65 n := 2 * (len(s) + 1) / 5
66 if n != 6 && n != 8 && n != 20 {
67 goto error
68 }
69 hw = make(HardwareAddr, n)
70 for x, i := 0, 0; i < n; i += 2 {
71 var ok bool
72 if hw[i], ok = xtoi2(s[x:x+2], 0); !ok {
73 goto error
74 }
75 if hw[i+1], ok = xtoi2(s[x+2:], s[4]); !ok {
76 goto error
77 }
78 x += 5
79 }
80 } else {
81 if len(s)%2 != 0 {
82 goto error
83 }
84
85 n := len(s) / 2
86 if n != 6 && n != 8 && n != 20 {
87 goto error
88 }
89
90 hw = make(HardwareAddr, len(s)/2)
91 for x, i := 0, 0; i < n; i++ {
92 var ok bool
93 if hw[i], ok = xtoi2(s[x:x+2], 0); !ok {
94 goto error
95 }
96 x += 2
97 }
98 }
99 return hw, nil
100
101 error:
102 return nil, &AddrError{Err: "invalid MAC address", Addr: s}
103 }