-
Notifications
You must be signed in to change notification settings - Fork 75
/
net.go
69 lines (56 loc) · 1.44 KB
/
net.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
package npp
import (
"context"
"fmt"
"net"
"syscall"
"github.com/libp2p/go-reuseport"
"github.com/sonm-io/core/util/netutil"
)
const (
protocol = "tcp"
)
type Port uint16
// DialContext allows to dial the remote peer with SO_REUSEPORT and
// SO_REUSEADDR options configured.
func DialContext(ctx context.Context, network, laddr, raddr string) (net.Conn, error) {
if !reuseport.Available() {
return nil, syscall.ENOPROTOOPT
}
var dialer reuseport.Dialer
if laddr != "" {
localAddr, err := reuseport.ResolveAddr(network, laddr)
if err != nil {
return nil, err
}
dialer.D.LocalAddr = localAddr
}
return dialer.DialContext(ctx, network, raddr)
}
// PrivateAddrs collects and returns private addresses of a network interfaces
// the socket bind on.
func privateAddrs(addr net.Addr) ([]net.Addr, error) {
ip, port, err := netutil.SplitHostPort(addr.String())
if err != nil {
return nil, err
}
if !ip.IsUnspecified() {
return []net.Addr{addr}, nil
}
// For unspecified bind addresses, actual address set has to be resolved.
// In other words, unspecified means every available (but still private)
// address for the host.
ips, err := netutil.GetAvailableIPs()
if err != nil {
return nil, err
}
var addrs []net.Addr
for _, ip := range ips {
addr, err := net.ResolveTCPAddr(protocol, fmt.Sprintf("%s:%d", ip, uint16(port)))
if err != nil {
return nil, err
}
addrs = append(addrs, addr)
}
return addrs, nil
}