| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- // Copyright 2019 Yunion
- //
- // Licensed under the Apache License, Version 2.0 (the "License");
- // you may not use this file except in compliance with the License.
- // You may obtain a copy of the License at
- //
- // http://www.apache.org/licenses/LICENSE-2.0
- //
- // Unless required by applicable law or agreed to in writing, software
- // distributed under the License is distributed on an "AS IS" BASIS,
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- // See the License for the specific language governing permissions and
- // limitations under the License.
- package netutils2
- import (
- "yunion.io/x/log"
- "yunion.io/x/pkg/util/netutils"
- )
- type SNicInfo struct {
- IpAddr string
- Gateway string
- Ip6Addr string
- Gateway6 string
- MacAddr string
- IsDefault bool
- }
- type SNicInfoList []SNicInfo
- func (nics SNicInfoList) Add(mac, ip, gw, ip6, gw6 string, isDefault bool) SNicInfoList {
- return append(nics, SNicInfo{
- IpAddr: ip,
- MacAddr: mac,
- Gateway: gw,
- Ip6Addr: ip6,
- Gateway6: gw6,
- IsDefault: isDefault,
- })
- }
- func (nics SNicInfoList) FindDefaultNicMac() (string, int) {
- var intMac, exitMac, defMac string
- var intIdx, exitIdx, defIdx int
- for i, nic := range nics {
- if len(nic.IpAddr) == 0 && len(nic.Ip6Addr) == 0 {
- continue
- }
- if len(nic.IpAddr) > 0 && len(nic.Gateway) == 0 {
- continue
- }
- if len(nic.Ip6Addr) > 0 && len(nic.Gateway6) == 0 {
- continue
- }
- var isExit bool
- if len(nic.IpAddr) > 0 {
- addr, err := netutils.NewIPV4Addr(nic.IpAddr)
- if err != nil {
- log.Errorf("NewIPV4Addr %s fail %s", nic.IpAddr, err)
- continue
- }
- isExit = netutils.IsExitAddress(addr)
- }
- if len(exitMac) == 0 || len(intMac) == 0 || len(defMac) == 0 {
- if len(exitMac) == 0 && isExit {
- exitMac = nic.MacAddr
- exitIdx = i
- }
- if len(intMac) == 0 && !isExit {
- intMac = nic.MacAddr
- intIdx = i
- }
- if len(defMac) == 0 && nic.IsDefault && !isExit {
- defMac = nic.MacAddr
- defIdx = i
- }
- } else if len(exitMac) > 0 && len(intMac) > 0 && len(defMac) > 0 {
- break
- }
- }
- if len(exitMac) > 0 {
- return exitMac, exitIdx
- }
- if len(defMac) > 0 {
- return defMac, defIdx
- }
- if len(intMac) > 0 {
- return intMac, intIdx
- }
- return "", -1
- }
|