-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathoptions.go
79 lines (71 loc) · 1.77 KB
/
options.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
67
68
69
70
71
72
73
74
75
76
77
78
79
package retryabledns
import (
"errors"
"fmt"
"net"
"time"
)
var (
ErrMaxRetriesZero = errors.New("retries must be at least 1")
ErrResolversEmpty = errors.New("resolvers list must not be empty")
)
type Options struct {
BaseResolvers []string
MaxRetries int
Timeout time.Duration
Hostsfile bool
LocalAddrIP net.IP
LocalAddrPort uint16
ConnectionPoolThreads int
MaxPerCNAMEFollows int
Proxy string
}
// Returns a net.Addr of a UDP or TCP type depending on whats required
func (options *Options) GetLocalAddr(proto Protocol) net.Addr {
if options.LocalAddrIP == nil {
return nil
}
ipPort := net.JoinHostPort(options.LocalAddrIP.String(), fmt.Sprint(options.LocalAddrPort))
var ipAddr net.Addr
switch proto {
case UDP:
ipAddr, _ = net.ResolveUDPAddr("udp", ipPort)
default:
ipAddr, _ = net.ResolveTCPAddr("tcp", ipPort)
}
return ipAddr
}
// Sets the ip from a string, if invalid sets as nil
func (options *Options) SetLocalAddrIP(ip string) {
// invalid ips are no-ops
options.LocalAddrIP = net.ParseIP(ip)
}
// Sets the first available IP from a network interface name e.g. eth0
func (options *Options) SetLocalAddrIPFromNetInterface(ifaceName string) error {
iface, err := net.InterfaceByName(ifaceName)
if err != nil {
return err
}
addrs, err := iface.Addrs()
if err != nil {
return err
}
for _, addr := range addrs {
ipnetAddr, ok := addr.(*net.IPNet)
if !ok {
continue
}
options.LocalAddrIP = ipnetAddr.IP
return nil
}
return errors.New("no ip address found for interface")
}
func (options *Options) Validate() error {
if options.MaxRetries == 0 {
return ErrMaxRetriesZero
}
if len(options.BaseResolvers) == 0 {
return ErrResolversEmpty
}
return nil
}