chore: consolidate various randomPort() implementations (#12362)

Consolidates our existing randomPort() implementations to package testutil
This commit is contained in:
Cian Johnston
2024-02-29 12:51:44 +00:00
committed by GitHub
parent 4f87ba46f9
commit eba8cd7c07
6 changed files with 52 additions and 42 deletions
+1 -16
View File
@@ -8,7 +8,6 @@ import (
"errors"
"fmt"
"io"
"math/rand"
"net"
"net/http"
"net/http/httptest"
@@ -838,7 +837,7 @@ func TestAgent_TCPRemoteForwarding(t *testing.T) {
var ll net.Listener
var err error
for {
randomPort = pickRandomPort()
randomPort = testutil.RandomPortNoListen(t)
addr := net.TCPAddrFromAddrPort(netip.AddrPortFrom(localhost, randomPort))
ll, err = sshClient.ListenTCP(addr)
if err != nil {
@@ -2666,20 +2665,6 @@ func (s *syncWriter) Write(p []byte) (int, error) {
return s.w.Write(p)
}
// pickRandomPort picks a random port number for the ephemeral range. We do this entirely randomly
// instead of opening a listener and closing it to find a port that is likely to be free, since
// sometimes the OS reallocates the port very quickly.
func pickRandomPort() uint16 {
const (
// Overlap of windows, linux in https://en.wikipedia.org/wiki/Ephemeral_port
min = 49152
max = 60999
)
n := max - min
x := rand.Intn(n) //nolint: gosec
return uint16(min + x)
}
// echoOnce accepts a single connection, reads 4 bytes and echos them back
func echoOnce(t *testing.T, ll net.Listener) {
t.Helper()