|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "net" |
| 6 | + |
| 7 | + apimachinerynet "k8s.io/apimachinery/pkg/util/net" |
| 8 | +) |
| 9 | + |
| 10 | +var ( |
| 11 | + ErrNoAutoInterface = fmt.Errorf("no auto interface found") |
| 12 | + ErrBestInterfaceWas6 = fmt.Errorf("best interface was IPv6") |
| 13 | + ErrCannotDetermineInterfaceName = fmt.Errorf("cannot determine interface name") |
| 14 | +) |
| 15 | + |
| 16 | +// determineBestNetworkInterface attempts to determine the best network interface to use for the cluster. |
| 17 | +func determineBestNetworkInterface() (string, error) { |
| 18 | + iface, err := apimachinerynet.ChooseHostInterface() |
| 19 | + |
| 20 | + if err != nil || iface == nil { |
| 21 | + return "", ErrNoAutoInterface |
| 22 | + } |
| 23 | + |
| 24 | + if iface.To4() == nil { |
| 25 | + return "", ErrBestInterfaceWas6 |
| 26 | + } |
| 27 | + |
| 28 | + ifaceName, err := findInterfaceNameByIP(iface) |
| 29 | + if err != nil { |
| 30 | + return "", ErrCannotDetermineInterfaceName |
| 31 | + } |
| 32 | + |
| 33 | + return ifaceName, nil |
| 34 | +} |
| 35 | + |
| 36 | +func findInterfaceNameByIP(ip net.IP) (string, error) { |
| 37 | + interfaces, err := net.Interfaces() |
| 38 | + if err != nil { |
| 39 | + return "", fmt.Errorf("failed to list interfaces: %v", err) |
| 40 | + } |
| 41 | + |
| 42 | + for _, iface := range interfaces { |
| 43 | + addrs, err := iface.Addrs() |
| 44 | + if err != nil { |
| 45 | + return "", fmt.Errorf("failed to get addresses for interface %s: %v", iface.Name, err) |
| 46 | + } |
| 47 | + |
| 48 | + for _, addr := range addrs { |
| 49 | + var ifaceIP net.IP |
| 50 | + switch v := addr.(type) { |
| 51 | + case *net.IPNet: |
| 52 | + ifaceIP = v.IP |
| 53 | + case *net.IPAddr: |
| 54 | + ifaceIP = v.IP |
| 55 | + } |
| 56 | + |
| 57 | + if ifaceIP != nil && ifaceIP.Equal(ip) { |
| 58 | + return iface.Name, nil |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + return "", fmt.Errorf("no interface found for IP %s", ip) |
| 64 | +} |
0 commit comments