You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.1 KiB

4 years ago
  1. package util
  2. import (
  3. "net"
  4. "strconv"
  5. "strings"
  6. "github.com/seaweedfs/seaweedfs/weed/glog"
  7. )
  8. func DetectedHostAddress() string {
  9. netInterfaces, err := net.Interfaces()
  10. if err != nil {
  11. glog.V(0).Infof("failed to detect net interfaces: %v", err)
  12. return ""
  13. }
  14. if v4Address := selectIpV4(netInterfaces); v4Address != "" {
  15. return v4Address
  16. }
  17. return "localhost"
  18. }
  19. func selectIpV4(netInterfaces []net.Interface) string {
  20. for _, netInterface := range netInterfaces {
  21. if (netInterface.Flags & net.FlagUp) == 0 {
  22. continue
  23. }
  24. addrs, err := netInterface.Addrs()
  25. if err != nil {
  26. glog.V(0).Infof("get interface addresses: %v", err)
  27. }
  28. for _, a := range addrs {
  29. if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
  30. if ipNet.IP.To4() != nil && ipNet.IP.To16() == nil || ipNet.IP.To16() != nil && ipNet.IP.To4() == nil{
  31. return ipNet.IP.String()
  32. }
  33. }
  34. }
  35. }
  36. return ""
  37. }
  38. func JoinHostPort(host string, port int) string {
  39. portStr := strconv.Itoa(port)
  40. if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
  41. return host + ":" + portStr
  42. }
  43. return net.JoinHostPort(host, portStr)
  44. }