-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathport.go
More file actions
49 lines (42 loc) · 786 Bytes
/
port.go
File metadata and controls
49 lines (42 loc) · 786 Bytes
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
package main
import (
"fmt"
"math/rand"
"net"
"sync"
"time"
)
var (
usedPorts = make(map[int]bool)
portMutex sync.Mutex
randomSource = rand.New(rand.NewSource(time.Now().UnixNano()))
)
func isPortAvailable(port int) bool {
addr := net.JoinHostPort("0.0.0.0", fmt.Sprintf("%d", port))
ln, err := net.Listen("tcp", addr)
if err != nil {
return false
}
_ = ln.Close()
return true
}
func GenerateUniquePort() int {
const minPort = 10000
const maxPort = 65525
portMutex.Lock()
defer portMutex.Unlock()
if len(usedPorts) >= (maxPort - minPort + 1) {
return -1
}
for {
port := randomSource.Intn(maxPort-minPort+1) + minPort
if usedPorts[port] {
continue
}
if !isPortAvailable(port) {
continue
}
usedPorts[port] = true
return port
}
}