summaryrefslogtreecommitdiff
path: root/utils/ports.go
blob: eea060433eb74e4397b1c0e3335c7347a9baf429 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package utils

import (
	"fmt"
	"net"
	"strconv"
)

// Find a random, open port on the host.
func GetRandomPort() (int, error) {
	l, err := net.Listen("tcp", ":0")
	if err != nil {
		return 0, fmt.Errorf("unable to get free TCP port: %w", err)
	}
	defer l.Close()
	_, randomPort, err := net.SplitHostPort(l.Addr().String())
	if err != nil {
		return 0, fmt.Errorf("unable to determine free port: %w", err)
	}
	rp, err := strconv.Atoi(randomPort)
	if err != nil {
		return 0, fmt.Errorf("unable to convert random port to int: %w", err)
	}
	return rp, nil
}