mirror of
https://github.com/containers/podman.git
synced 2025-05-17 06:59:07 +08:00

We now use the golang error wrapping format specifier `%w` instead of the deprecated github.com/pkg/errors package. [NO NEW TESTS NEEDED] Signed-off-by: Sascha Grunert <sgrunert@redhat.com>
26 lines
556 B
Go
26 lines
556 B
Go
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
|
|
}
|