summaryrefslogtreecommitdiff
path: root/pkg/helper/ports.go
diff options
context:
space:
mode:
authorkali kaneko (leap communications) <kali@leap.se>2020-02-27 18:06:22 +0100
committerkali kaneko (leap communications) <kali@leap.se>2020-04-30 22:10:16 +0200
commit79b2cf15c8d563dc5a3ea589ea1c4a29ee1315e8 (patch)
tree31a4b799028f0dbc5ea5b2a7e0285e41d8b97a8e /pkg/helper/ports.go
parentd1bbf9609672409120c23f989c1298fbb8b66152 (diff)
[feat] listen on available port
Diffstat (limited to 'pkg/helper/ports.go')
-rw-r--r--pkg/helper/ports.go49
1 files changed, 49 insertions, 0 deletions
diff --git a/pkg/helper/ports.go b/pkg/helper/ports.go
new file mode 100644
index 0000000..58e5856
--- /dev/null
+++ b/pkg/helper/ports.go
@@ -0,0 +1,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
+}