macutils.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package netutils
  15. import (
  16. "fmt"
  17. "strconv"
  18. "strings"
  19. )
  20. type SMacAddr [6]byte
  21. func ErrMacFormat(macStr string) error {
  22. return fmt.Errorf("invalid mac format: %s", macStr)
  23. }
  24. func ParseMac(macStr string) (SMacAddr, error) {
  25. mac := SMacAddr{}
  26. macStr = FormatMacAddr(macStr)
  27. parts := strings.Split(macStr, ":")
  28. if len(parts) != 6 {
  29. return mac, ErrMacFormat(macStr)
  30. }
  31. for i := 0; i < 6; i += 1 {
  32. bt, err := strconv.ParseInt(parts[i], 16, 64)
  33. if err != nil {
  34. return mac, ErrMacFormat(macStr)
  35. }
  36. mac[i] = byte(bt)
  37. }
  38. return mac, nil
  39. }
  40. func (mac SMacAddr) Add(step int) SMacAddr {
  41. mac2 := SMacAddr{}
  42. leftOver := step
  43. for i := 5; i >= 0; i -= 1 {
  44. newByte := int(mac[i]) + leftOver
  45. res := 0
  46. if newByte < 0 {
  47. res = ((-newByte) / 0x100) + 1
  48. newByte = newByte + res*0x100
  49. }
  50. mac2[i] = byte(newByte % 0x100)
  51. leftOver = newByte/0x100 - res
  52. }
  53. return mac2
  54. }
  55. func (mac SMacAddr) String() string {
  56. var parts [6]string
  57. for i := 0; i < len(parts); i += 1 {
  58. parts[i] = fmt.Sprintf("%02x", mac[i])
  59. }
  60. return strings.Join(parts[:], ":")
  61. }