github.com/ader1990/go@v0.0.0-20140630135419-8c24447fa791/src/pkg/net/mac.go (about)

     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  // MAC address manipulations
     6  
     7  package net
     8  
     9  import "errors"
    10  
    11  const hexDigit = "0123456789abcdef"
    12  
    13  // A HardwareAddr represents a physical hardware address.
    14  type HardwareAddr []byte
    15  
    16  func (a HardwareAddr) String() string {
    17  	if len(a) == 0 {
    18  		return ""
    19  	}
    20  	buf := make([]byte, 0, len(a)*3-1)
    21  	for i, b := range a {
    22  		if i > 0 {
    23  			buf = append(buf, ':')
    24  		}
    25  		buf = append(buf, hexDigit[b>>4])
    26  		buf = append(buf, hexDigit[b&0xF])
    27  	}
    28  	return string(buf)
    29  }
    30  
    31  // ParseMAC parses s as an IEEE 802 MAC-48, EUI-48, or EUI-64 using one of the
    32  // following formats:
    33  //   01:23:45:67:89:ab
    34  //   01:23:45:67:89:ab:cd:ef
    35  //   01-23-45-67-89-ab
    36  //   01-23-45-67-89-ab-cd-ef
    37  //   0123.4567.89ab
    38  //   0123.4567.89ab.cdef
    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 {
    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 {
    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, errors.New("invalid MAC address: " + s)
    86  }