summaryrefslogtreecommitdiff
path: root/pkg/specgen/ports.go
diff options
context:
space:
mode:
Diffstat (limited to 'pkg/specgen/ports.go')
-rw-r--r--pkg/specgen/ports.go26
1 files changed, 26 insertions, 0 deletions
diff --git a/pkg/specgen/ports.go b/pkg/specgen/ports.go
new file mode 100644
index 000000000..940b2a564
--- /dev/null
+++ b/pkg/specgen/ports.go
@@ -0,0 +1,26 @@
+package specgen
+
+import (
+ "net"
+ "strconv"
+
+ "github.com/pkg/errors"
+)
+
+// Find a random, open port on the host
+func GetRandomPort() (int, error) {
+ l, err := net.Listen("tcp", ":0")
+ if err != nil {
+ return 0, errors.Wrapf(err, "unable to get free TCP port")
+ }
+ defer l.Close()
+ _, randomPort, err := net.SplitHostPort(l.Addr().String())
+ if err != nil {
+ return 0, errors.Wrapf(err, "unable to determine free port")
+ }
+ rp, err := strconv.Atoi(randomPort)
+ if err != nil {
+ return 0, errors.Wrapf(err, "unable to convert random port to int")
+ }
+ return rp, nil
+}