-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdort.go
112 lines (96 loc) · 2.08 KB
/
dort.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Package dort exposes functionality to get free (unused) ports on your
// system.
package dort
import (
"fmt"
"math/rand"
"net"
"strconv"
"sync"
"time"
)
const (
lowPort = 10000
maxPorts = 65535
blockSize = 1024
maxBlocks = 16
attempts = 10
)
var (
port int
firstPort int
once sync.Once
mu sync.Mutex
lnLock sync.Mutex
lockLn net.Listener
)
// Get returns n ports that are free to use, panicing if it can't succeed.
func Get(n int) []int {
ports, err := GetWithErr(n)
if err != nil {
panic(err)
}
return ports
}
// GetS returns n ports as strings that are free to use, panicing if it can't succeed.
func GetS(n int) []string {
ports, err := GetSWithErr(n)
if err != nil {
panic(err)
}
return ports
}
// GetS return n ports (as strings) that are free to use.
func GetSWithErr(n int) ([]string, error) {
ports, err := GetWithErr(n)
if err != nil {
return nil, err
}
var portsStr []string
for _, port := range ports {
portsStr = append(portsStr, strconv.Itoa(port))
}
return portsStr, nil
}
// Get returns n ports that are free to use.
func GetWithErr(n int) (ports []int, err error) {
mu.Lock()
defer mu.Unlock()
if n > blockSize-1 {
return nil, fmt.Errorf("dort: block size is too small for ports requested")
}
once.Do(initialize)
for len(ports) < n {
port++
if port < firstPort+1 || port >= firstPort+blockSize {
port = firstPort + 1
}
ln, err := listen(port)
if err != nil {
continue
}
ln.Close()
ports = append(ports, port)
}
return ports, nil
}
func initialize() {
if lowPort+maxBlocks*blockSize > maxPorts {
panic("dort: block size is too big or too many blocks requested")
}
rand.Seed(time.Now().UnixNano())
var err error
for i := 0; i < attempts; i++ {
block := int(rand.Int31n(int32(maxBlocks)))
firstPort = lowPort + block*blockSize
lockLn, err = listen(firstPort)
if err != nil {
continue
}
return
}
panic("dort: can't allocated port block")
}
func listen(port int) (*net.TCPListener, error) {
return net.ListenTCP("tcp", &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: port})
}