summaryrefslogtreecommitdiff
path: root/pkg/helper/ports.go
blob: 58e5856c26bfde61ad9a5c2793eec094f3d35375 (plain)
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 helper

import (
	"io/ioutil"
	"net"
	"os"
	"path"
	"strconv"
)

func getFirstAvailablePortFrom(port int) int {
	for {
		if isPortAvailable(port) {
			return port
		}
		if port > 65535 {
			return 0
		}
		port += 1
	}
}

func isPortAvailable(port int) bool {
	conn, err := net.Dial("tcp", "127.0.0.1:"+strconv.Itoa(port))
	if err != nil {
		return true
	} else {
		defer conn.Close()
		return false
	}
}

func writePortToFile(port int) error {
	exeDir, err := getExecutableDir()
	if err != nil {
		return err
	}
	portFile := path.Join(exeDir, "port")
	return ioutil.WriteFile(portFile, []byte(strconv.Itoa(port)+"\n"), 0644)

}

func getExecutableDir() (string, error) {
	ex, err := os.Executable()
	if err != nil {
		return "", err
	}
	return path.Dir(ex), nil
}