Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 32 additions & 4 deletions pkg/netutils/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -362,17 +364,43 @@ 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
// interface.
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
}