diff --git a/pkg/netutils/interface.go b/pkg/netutils/interface.go index 4d27ba80c..9f7aa7e35 100644 --- a/pkg/netutils/interface.go +++ b/pkg/netutils/interface.go @@ -7,10 +7,12 @@ import ( "io" "net" "os" - "strings" + "github.com/alibaba/pouch/pkg/exec" + "github.com/golang/glog" + "github.com/pkg/errors" ) // AddressFamily is the ip address type. @@ -362,6 +364,26 @@ func chooseHostInterfaceFromRoute(routes []Route, nw networkInterfacer) (net.IP, return nil, fmt.Errorf("unable to select an IP from default routes") } +func getAddrByHostname() (net.IP, error) { + exit, stdout, stderr, err := exec.Run(0, "hostname", "-i") + if err != nil { + return nil, errors.Wrapf(err, "failed to get ip address, stdout: (%s), stderr: (%s), exit: (%s)", + stdout, stderr, exit) + } + + if exit != 0 { + return nil, errors.Errorf("failed to get ip address, stdout: (%s), stderr: (%s), exit: (%s)", + stdout, stderr, exit) + } + + addr := net.ParseIP(strings.TrimSpace(stdout)) + if addr == nil { + return nil, errors.Errorf("failed to get ip address, invalid format: (%s)", stdout) + } + + return addr, nil +} + // ChooseBindAddress is used to choose an Host IP address for binding. // If bind-address is usable, return it directly // If bind-address is not usable (unset, 0.0.0.0, or loopback), we will use the host's default @@ -369,10 +391,16 @@ func chooseHostInterfaceFromRoute(routes []Route, nw networkInterfacer) (net.IP, func ChooseBindAddress(bindAddress net.IP) (net.IP, error) { if bindAddress == nil || bindAddress.IsUnspecified() || bindAddress.IsLoopback() { hostIP, err := ChooseHostInterface() - if err != nil { - return nil, err + if err == nil { + bindAddress = hostIP + } else { + hostIP, err = getAddrByHostname() + if err != nil { + return nil, err + } + bindAddress = hostIP } - bindAddress = hostIP + } return bindAddress, nil }