Skip to content

Commit

Permalink
Merge branch 'main' into romain.marcadier/alb-event/APPSEC-42909
Browse files Browse the repository at this point in the history
  • Loading branch information
RomainMuller authored Jan 16, 2024
2 parents ff51aa2 + a27fe22 commit 3f3a264
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions pkg/networkdevice/testutils/freeport.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,36 @@ package testutils

import (
"net"
"sync"
)

var (
globalMutex sync.Mutex // Prevent the util function to be called concurrently
usedPorts = make(map[uint16]bool)
)

// GetFreePort finds a free port to use for testing.
// Borrowed from: https://github.com/phayes/freeport/blame/master/freeport.go#L8-L20
func GetFreePort() (uint16, error) {
globalMutex.Lock()
defer globalMutex.Unlock()

var lastError error
for retries := 0; retries < 5; retries++ {
port, err := getSingleFreePort()
if err != nil {
lastError = err
continue
}
if _, ok := usedPorts[port]; !ok {
usedPorts[port] = true
return port, nil
}
}
return 0, lastError
}

func getSingleFreePort() (uint16, error) {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return 0, err
Expand Down

0 comments on commit 3f3a264

Please sign in to comment.