seaweedfs/weed/util/network.go

63 lines
1.3 KiB
Go
Raw Normal View History

package util
import (
"net"
2021-09-08 07:43:54 +08:00
"strconv"
"strings"
"github.com/seaweedfs/seaweedfs/weed/glog"
)
func DetectedHostAddress() string {
netInterfaces, err := net.Interfaces()
if err != nil {
glog.V(0).Infof("failed to detect net interfaces: %v", err)
return ""
}
2021-09-15 01:37:06 +08:00
if v4Address := selectIpV4(netInterfaces, true); v4Address != "" {
2021-09-08 10:29:42 +08:00
return v4Address
}
2021-09-15 01:37:06 +08:00
if v6Address := selectIpV4(netInterfaces, false); v6Address != "" {
2021-09-08 10:29:42 +08:00
return v6Address
}
return "localhost"
}
func selectIpV4(netInterfaces []net.Interface, isIpV4 bool) string {
for _, netInterface := range netInterfaces {
if (netInterface.Flags & net.FlagUp) == 0 {
continue
}
addrs, err := netInterface.Addrs()
if err != nil {
glog.V(0).Infof("get interface addresses: %v", err)
}
for _, a := range addrs {
if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
2021-09-08 10:29:42 +08:00
if isIpV4 {
if ipNet.IP.To4() != nil {
return ipNet.IP.String()
}
} else {
if ipNet.IP.To16() != nil {
return ipNet.IP.String()
}
}
}
}
}
2021-09-08 10:29:42 +08:00
return ""
}
2021-09-08 07:43:54 +08:00
func JoinHostPort(host string, port int) string {
portStr := strconv.Itoa(port)
if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
return host + ":" + portStr
}
return net.JoinHostPort(host, portStr)
2021-09-15 01:37:06 +08:00
}