Retro68/gcc/libgo/go/net/mac.go

86 lines
1.9 KiB
Go
Raw Normal View History

2012-03-27 23:13:14 +00:00
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package net
2014-09-21 17:33:12 +00:00
const hexDigit = "0123456789abcdef"
2012-03-27 23:13:14 +00:00
// A HardwareAddr represents a physical hardware address.
type HardwareAddr []byte
func (a HardwareAddr) String() string {
2014-09-21 17:33:12 +00:00
if len(a) == 0 {
return ""
}
buf := make([]byte, 0, len(a)*3-1)
2012-03-27 23:13:14 +00:00
for i, b := range a {
if i > 0 {
2014-09-21 17:33:12 +00:00
buf = append(buf, ':')
2012-03-27 23:13:14 +00:00
}
2014-09-21 17:33:12 +00:00
buf = append(buf, hexDigit[b>>4])
buf = append(buf, hexDigit[b&0xF])
2012-03-27 23:13:14 +00:00
}
2014-09-21 17:33:12 +00:00
return string(buf)
2012-03-27 23:13:14 +00:00
}
2017-04-10 11:32:00 +00:00
// ParseMAC parses s as an IEEE 802 MAC-48, EUI-48, EUI-64, or a 20-octet
// IP over InfiniBand link-layer address using one of the following formats:
2012-03-27 23:13:14 +00:00
// 01:23:45:67:89:ab
// 01:23:45:67:89:ab:cd:ef
2017-04-10 11:32:00 +00:00
// 01:23:45:67:89:ab:cd:ef:00:00:01:23:45:67:89:ab:cd:ef:00:00
2012-03-27 23:13:14 +00:00
// 01-23-45-67-89-ab
// 01-23-45-67-89-ab-cd-ef
2017-04-10 11:32:00 +00:00
// 01-23-45-67-89-ab-cd-ef-00-00-01-23-45-67-89-ab-cd-ef-00-00
2012-03-27 23:13:14 +00:00
// 0123.4567.89ab
// 0123.4567.89ab.cdef
2017-04-10 11:32:00 +00:00
// 0123.4567.89ab.cdef.0000.0123.4567.89ab.cdef.0000
2012-03-27 23:13:14 +00:00
func ParseMAC(s string) (hw HardwareAddr, err error) {
if len(s) < 14 {
goto error
}
if s[2] == ':' || s[2] == '-' {
if (len(s)+1)%3 != 0 {
goto error
}
n := (len(s) + 1) / 3
2017-04-10 11:32:00 +00:00
if n != 6 && n != 8 && n != 20 {
2012-03-27 23:13:14 +00:00
goto error
}
hw = make(HardwareAddr, n)
for x, i := 0, 0; i < n; i++ {
var ok bool
if hw[i], ok = xtoi2(s[x:], s[2]); !ok {
goto error
}
x += 3
}
} else if s[4] == '.' {
if (len(s)+1)%5 != 0 {
goto error
}
n := 2 * (len(s) + 1) / 5
2017-04-10 11:32:00 +00:00
if n != 6 && n != 8 && n != 20 {
2012-03-27 23:13:14 +00:00
goto error
}
hw = make(HardwareAddr, n)
for x, i := 0, 0; i < n; i += 2 {
var ok bool
if hw[i], ok = xtoi2(s[x:x+2], 0); !ok {
goto error
}
if hw[i+1], ok = xtoi2(s[x+2:], s[4]); !ok {
goto error
}
x += 5
}
} else {
goto error
}
return hw, nil
error:
2017-04-10 11:32:00 +00:00
return nil, &AddrError{Err: "invalid MAC address", Addr: s}
2012-03-27 23:13:14 +00:00
}