defgw.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 netutils2
  15. import (
  16. "yunion.io/x/log"
  17. "yunion.io/x/pkg/util/netutils"
  18. )
  19. type SNicInfo struct {
  20. IpAddr string
  21. Gateway string
  22. Ip6Addr string
  23. Gateway6 string
  24. MacAddr string
  25. IsDefault bool
  26. }
  27. type SNicInfoList []SNicInfo
  28. func (nics SNicInfoList) Add(mac, ip, gw, ip6, gw6 string, isDefault bool) SNicInfoList {
  29. return append(nics, SNicInfo{
  30. IpAddr: ip,
  31. MacAddr: mac,
  32. Gateway: gw,
  33. Ip6Addr: ip6,
  34. Gateway6: gw6,
  35. IsDefault: isDefault,
  36. })
  37. }
  38. func (nics SNicInfoList) FindDefaultNicMac() (string, int) {
  39. var intMac, exitMac, defMac string
  40. var intIdx, exitIdx, defIdx int
  41. for i, nic := range nics {
  42. if len(nic.IpAddr) == 0 && len(nic.Ip6Addr) == 0 {
  43. continue
  44. }
  45. if len(nic.IpAddr) > 0 && len(nic.Gateway) == 0 {
  46. continue
  47. }
  48. if len(nic.Ip6Addr) > 0 && len(nic.Gateway6) == 0 {
  49. continue
  50. }
  51. var isExit bool
  52. if len(nic.IpAddr) > 0 {
  53. addr, err := netutils.NewIPV4Addr(nic.IpAddr)
  54. if err != nil {
  55. log.Errorf("NewIPV4Addr %s fail %s", nic.IpAddr, err)
  56. continue
  57. }
  58. isExit = netutils.IsExitAddress(addr)
  59. }
  60. if len(exitMac) == 0 || len(intMac) == 0 || len(defMac) == 0 {
  61. if len(exitMac) == 0 && isExit {
  62. exitMac = nic.MacAddr
  63. exitIdx = i
  64. }
  65. if len(intMac) == 0 && !isExit {
  66. intMac = nic.MacAddr
  67. intIdx = i
  68. }
  69. if len(defMac) == 0 && nic.IsDefault && !isExit {
  70. defMac = nic.MacAddr
  71. defIdx = i
  72. }
  73. } else if len(exitMac) > 0 && len(intMac) > 0 && len(defMac) > 0 {
  74. break
  75. }
  76. }
  77. if len(exitMac) > 0 {
  78. return exitMac, exitIdx
  79. }
  80. if len(defMac) > 0 {
  81. return defMac, defIdx
  82. }
  83. if len(intMac) > 0 {
  84. return intMac, intIdx
  85. }
  86. return "", -1
  87. }