mac.mx 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 := []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  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