mirror of
https://github.com/libp2p/go-libp2p.git
synced 2025-10-16 05:00:49 +08:00
chore: add tests for examples
This commit is contained in:
37
examples/testutils/net.go
Normal file
37
examples/testutils/net.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package testutils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// FindFreePort attempts to find an unused tcp port
|
||||
func FindFreePort(t *testing.T, host string, maxAttempts int) (int, error) {
|
||||
t.Helper()
|
||||
|
||||
if host == "" {
|
||||
host = "localhost"
|
||||
}
|
||||
|
||||
for i := 0; i < maxAttempts; i++ {
|
||||
addr, err := net.ResolveTCPAddr("tcp", net.JoinHostPort(host, "0"))
|
||||
if err != nil {
|
||||
t.Logf("unable to resolve tcp addr: %v", err)
|
||||
continue
|
||||
}
|
||||
l, err := net.ListenTCP("tcp", addr)
|
||||
if err != nil {
|
||||
l.Close()
|
||||
t.Logf("unable to listen on addr %q: %v", addr, err)
|
||||
continue
|
||||
}
|
||||
|
||||
port := l.Addr().(*net.TCPAddr).Port
|
||||
l.Close()
|
||||
return port, nil
|
||||
|
||||
}
|
||||
|
||||
return 0, fmt.Errorf("no free port found")
|
||||
}
|
Reference in New Issue
Block a user