summaryrefslogtreecommitdiff
path: root/network/network.go
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2025-04-07 21:31:09 +0200
committerSanto Cariotti <santo@dcariotti.me>2025-04-07 21:31:09 +0200
commitf75ec8f8f5b3d0d75f752b26df1088e9d42d2634 (patch)
tree911a4bac5f8457c6029ec7e555f2081f98245a4f /network/network.go
parentd35c26ecc61103b4ba7d484acf76b6a969159518 (diff)
Join a game
Diffstat (limited to 'network/network.go')
-rw-r--r--network/network.go14
1 files changed, 14 insertions, 0 deletions
diff --git a/network/network.go b/network/network.go
index 322487b..5ab2dac 100644
--- a/network/network.go
+++ b/network/network.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"log/slog"
+ "math/rand"
"net"
"sync"
"time"
@@ -224,3 +225,16 @@ func GetOutboundIP() net.IP {
return localAddr.IP
}
+
+func GetRandomAvailablePort() (int, error) {
+ for i := 0; i < 100; i += 1 {
+ port := rand.Intn(65535-1024) + 1024
+ addr := fmt.Sprintf(":%d", port)
+ ln, err := net.Listen("tcp", addr)
+ if err == nil {
+ defer ln.Close()
+ return port, nil
+ }
+ }
+ return 0, fmt.Errorf("failed to find an available port after multiple attempts")
+}