internal/pkg/testing/port.go (14 lines of code) (raw):
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package testing
import "net"
// FreePort finds a free port on the system.
func FreePort() (uint16, error) {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return 0, err
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return 0, err
}
defer l.Close()
return uint16(l.Addr().(*net.TCPAddr).Port), nil //nolint:gosec // disable G115
}