-
Notifications
You must be signed in to change notification settings - Fork 0
/
transport.go
36 lines (30 loc) · 849 Bytes
/
transport.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
package integration
import (
"fmt"
"net"
)
const (
portRangeMax = 65535
)
var (
errPortMaxExceeded = portError{message: "port range exceeded"}
errNegativePortValue = portError{message: "cannot have a negative port value"}
)
type portError struct{ message string }
// Error returns a string with the port-related error message
func (p portError) Error() string {
return fmt.Sprintf("port discovery error: %s", p.message)
}
// GetOpenPortInRange finds an unused port within a specified range
func GetOpenPortInRange(lowerBound, upperBound int) (int, error) {
if lowerBound < 0 {
return -1, errNegativePortValue
}
for lowerBound <= portRangeMax && lowerBound <= upperBound {
if _, err := net.Dial("tcp", fmt.Sprintf(":%d", lowerBound)); err != nil {
return lowerBound, nil
}
lowerBound++
}
return -1, errPortMaxExceeded
}