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.

62 lines
1.3 KiB

3 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, true); v4Address != "" {
  15. return v4Address
  16. }
  17. if v6Address := selectIpV4(netInterfaces, false); v6Address != "" {
  18. return v6Address
  19. }
  20. return "localhost"
  21. }
  22. func selectIpV4(netInterfaces []net.Interface, isIpV4 bool) string {
  23. for _, netInterface := range netInterfaces {
  24. if (netInterface.Flags & net.FlagUp) == 0 {
  25. continue
  26. }
  27. addrs, err := netInterface.Addrs()
  28. if err != nil {
  29. glog.V(0).Infof("get interface addresses: %v", err)
  30. }
  31. for _, a := range addrs {
  32. if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
  33. if isIpV4 {
  34. if ipNet.IP.To4() != nil {
  35. return ipNet.IP.String()
  36. }
  37. } else {
  38. if ipNet.IP.To16() != nil {
  39. return ipNet.IP.String()
  40. }
  41. }
  42. }
  43. }
  44. }
  45. return ""
  46. }
  47. func JoinHostPort(host string, port int) string {
  48. portStr := strconv.Itoa(port)
  49. if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
  50. return host + ":" + portStr
  51. }
  52. return net.JoinHostPort(host, portStr)
  53. }