Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bugfix: get ip address by hostname -i #2367

Merged
merged 2 commits into from
Oct 31, 2018
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
}