@@ -21,6 +21,7 @@ import (
21
21
"net"
22
22
23
23
restclient "k8s.io/client-go/rest"
24
+ netutils "k8s.io/utils/net"
24
25
)
25
26
26
27
// LoopbackClientServerNameOverride is passed to the apiserver from the loopback client in order to
@@ -70,23 +71,27 @@ func LoopbackHostPort(bindAddress string) (string, string, error) {
70
71
return "" , "" , fmt .Errorf ("invalid server bind address: %q" , bindAddress )
71
72
}
72
73
73
- isIPv6 := net . ParseIP (host ). To4 () == nil
74
+ isIPv6 := netutils . IsIPv6String (host )
74
75
75
76
// Value is expected to be an IP or DNS name, not "0.0.0.0".
76
77
if host == "0.0.0.0" || host == "::" {
77
- host = "localhost"
78
78
// Get ip of local interface, but fall back to "localhost".
79
79
// Note that "localhost" is resolved with the external nameserver first with Go's stdlib.
80
80
// So if localhost.<yoursearchdomain> resolves, we don't get a 127.0.0.1 as expected.
81
- addrs , err := net .InterfaceAddrs ()
82
- if err == nil {
83
- for _ , address := range addrs {
84
- if ipnet , ok := address .(* net.IPNet ); ok && ipnet .IP .IsLoopback () && isIPv6 == (ipnet .IP .To4 () == nil ) {
85
- host = ipnet .IP .String ()
86
- break
87
- }
81
+ host = getLoopbackAddress (isIPv6 )
82
+ }
83
+ return host , port , nil
84
+ }
85
+
86
+ // getLoopbackAddress returns the ip address of local loopback interface. If any error occurs or loopback interface is not found, will fall back to "localhost"
87
+ func getLoopbackAddress (wantIPv6 bool ) string {
88
+ addrs , err := net .InterfaceAddrs ()
89
+ if err == nil {
90
+ for _ , address := range addrs {
91
+ if ipnet , ok := address .(* net.IPNet ); ok && ipnet .IP .IsLoopback () && wantIPv6 == netutils .IsIPv6 (ipnet .IP ) {
92
+ return ipnet .IP .String ()
88
93
}
89
94
}
90
95
}
91
- return host , port , nil
96
+ return "localhost"
92
97
}
0 commit comments