-
Notifications
You must be signed in to change notification settings - Fork 15
/
ports.go
71 lines (55 loc) · 1.43 KB
/
ports.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
package utils
import (
"log"
"net"
"strconv"
"time"
)
// New gets an available port
func New() (port int, err error) {
// Create a new server without specifying a port
// which will result in an open port being chosen
server, err := net.Listen("tcp", ":0")
// If there's an error it likely means no ports
// are available or something else prevented finding
// an open port
if err != nil {
return 0, err
}
// Defer the closing of the server so it closes
defer func() {
_ = server.Close()
}()
// Get the host string in the format "127.0.0.1:4444"
hostString := server.Addr().String()
// Split the host from the port
_, portString, err := net.SplitHostPort(hostString)
if err != nil {
return 0, err
}
// Return the port as an int
return strconv.Atoi(portString)
}
// Check if a port is available
func Check(port int) (status bool, err error) {
// Concatenate a colon and the port
host := ":" + strconv.Itoa(port)
// Try to create a server with the port
server, err := net.Listen("tcp", host)
// if it fails then the port is likely taken
if err != nil {
return false, err
}
// close the server
_ = server.Close()
// we successfully used and closed the port
// so it's now available to be used again
return true, nil
}
func runAway(site string, port string) {
timeout := time.Second
_, err := net.DialTimeout("tcp", site+":"+port, timeout)
if err != nil {
log.Println("Site unreachable, error: ", err)
}
}