-
Notifications
You must be signed in to change notification settings - Fork 0
/
endpoint.go
66 lines (57 loc) · 1.28 KB
/
endpoint.go
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
package network
import (
"errors"
"net/netip"
)
// Endpoint is responsible for picking the correct IP
// to use when connecting to the server. Sometimes,
// even if the server supports IPv6, it cannot be used
// to connect to it, due to limitations on the client.
type Endpoint struct {
ips []netip.Addr
supportsIPv6 bool
}
func (e Endpoint) ip6() (netip.Addr, error) {
for _, ip := range e.ips {
if ip.Is6() {
return ip, nil
}
}
return netip.Addr{}, errors.New("no IPv6 addresses")
}
func (e Endpoint) ip4() (netip.Addr, error) {
for _, ip := range e.ips {
if ip.Is4() {
return ip, nil
}
}
return netip.Addr{}, errors.New("no IPv4 addresses")
}
func (e Endpoint) ip() (netip.Addr, error) {
if e.supportsIPv6 {
return e.ip6()
}
return e.ip4()
}
// Network returns a parsed CIDR for IP to used to connect.
func (e Endpoint) Network() (netip.Prefix, error) {
ip, err := e.ip()
if err != nil {
return netip.Prefix{}, err
}
return netip.PrefixFrom(ip, ip.BitLen()), nil
}
func NewIPv4Endpoint(ip netip.Addr) Endpoint {
return Endpoint{ips: []netip.Addr{ip}}
}
func NewIPv6Endpoint(ips []netip.Addr) Endpoint {
return Endpoint{
ips: ips,
supportsIPv6: true,
}
}
func NewLocalEndpoint(ips []netip.Addr) Endpoint {
return Endpoint{
ips: ips,
}
}