aboutsummaryrefslogtreecommitdiff
path: root/weed/util/network.go
blob: f7dbeebb7c71fc435e89e0f1e0905b625bb07b54 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package util

import (
	"net"
	"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 ""
	}

	if v4Address := selectIpV4(netInterfaces, true); v4Address != "" {
		return v4Address
	}

	if v6Address := selectIpV4(netInterfaces, false); v6Address != "" {
		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() {
				if isIpV4 {
					if ipNet.IP.To4() != nil {
						return ipNet.IP.String()
					}
				} else {
					if ipNet.IP.To4() == nil && ipNet.IP.To16() != nil {
						// Filter out link-local IPv6 addresses (fe80::/10)
						// They require zone identifiers and are not suitable for server binding
						if !ipNet.IP.IsLinkLocalUnicast() {
							return ipNet.IP.String()
						}
					}
				}
			}
		}
	}
	return ""
}

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)
}

// GetVolumeServerId returns the volume server ID.
// If id is provided (non-empty after trimming), use it as the identifier.
// Otherwise, fall back to ip:port for backward compatibility.
func GetVolumeServerId(id, ip string, port int) string {
	volumeServerId := strings.TrimSpace(id)
	if volumeServerId == "" {
		volumeServerId = JoinHostPort(ip, port)
	}
	return volumeServerId
}