Skip to content
This repository was archived by the owner on Jan 17, 2021. It is now read-only.

Commit acc054b

Browse files
committed
Pick a random port to start code-server on
1 parent b16ba0b commit acc054b

File tree

1 file changed

+21
-13
lines changed

1 file changed

+21
-13
lines changed

main.go

+21-13
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ package main
22

33
import (
44
"context"
5-
"errors"
65
"flag"
76
"fmt"
7+
"math/rand"
88
"net"
99
"net/http"
1010
"os"
@@ -19,6 +19,10 @@ import (
1919
"go.coder.com/flog"
2020
)
2121

22+
func init() {
23+
rand.Seed(time.Now().Unix())
24+
}
25+
2226
func main() {
2327
skipSyncFlag := flag.Bool("skipsync", false, "skip syncing local settings and extensions to remote host")
2428
flag.Usage = func() {
@@ -74,9 +78,9 @@ mkdir -p ~/.local/share/code-server
7478
}
7579

7680
flog.Info("starting code-server...")
77-
localPort, err := scanAvailablePort()
81+
localPort, err := randomPort()
7882
if err != nil {
79-
flog.Fatal("failed to scan available port: %v", err)
83+
flog.Fatal("failed to find available port: %v", err)
8084
}
8185

8286
// Starts code-server and forwards the remote port.
@@ -153,20 +157,24 @@ func commandExists(name string) bool {
153157
return err == nil
154158
}
155159

156-
// scanAvailablePort scans 1024-4096 until an available port is found.
157-
func scanAvailablePort() (string, error) {
158-
for port := 1024; port < 4096; port++ {
160+
// randomPort picks a random port to start code-server on.
161+
func randomPort() (string, error) {
162+
const (
163+
minPort = 1024
164+
maxPort = 65535
165+
maxTries = 10
166+
)
167+
for i := 0; i < maxTries; i++ {
168+
port := rand.Intn(maxPort-minPort+1) + minPort
159169
l, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
160-
if err != nil {
161-
// If we have an error the port is taken.
162-
continue
170+
if err == nil {
171+
_ = l.Close()
172+
return strconv.Itoa(port), nil
163173
}
164-
_ = l.Close()
165-
166-
return strconv.Itoa(port), nil
174+
flog.Info("port taken: %d", port)
167175
}
168176

169-
return "", errors.New("no ports available")
177+
return "", xerrors.Errorf("max number of tries exceeded: %d", maxTries)
170178
}
171179

172180
func syncUserSettings(host string) error {

0 commit comments

Comments
 (0)