summaryrefslogtreecommitdiff
path: root/internal/network/ip.go
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2025-04-08 14:37:33 +0200
committerSanto Cariotti <santo@dcariotti.me>2025-04-08 14:39:13 +0200
commit1f0d9ec8452f15c27cd33c4e3874454c35993743 (patch)
treec453a31ae5eb823aaf48868eea9fc4daf65f108b /internal/network/ip.go
parentc5b10e28b358308d8349b940af09f64368172f2e (diff)
Use internal/pkg structure
Diffstat (limited to 'internal/network/ip.go')
-rw-r--r--internal/network/ip.go33
1 files changed, 33 insertions, 0 deletions
diff --git a/internal/network/ip.go b/internal/network/ip.go
new file mode 100644
index 0000000..0c6451e
--- /dev/null
+++ b/internal/network/ip.go
@@ -0,0 +1,33 @@
+package network
+
+import (
+ "fmt"
+ "log/slog"
+ "math/rand"
+ "net"
+)
+
+func GetOutboundIP() net.IP {
+ conn, err := net.Dial("udp", "8.8.8.8:80")
+ if err != nil {
+ slog.Error("err", err)
+ }
+ defer conn.Close()
+
+ localAddr := conn.LocalAddr().(*net.UDPAddr)
+
+ 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")
+}