Files
go-libp2p/examples/testutils/net.go
Marten Seemann d2398ee4f2 quic: update quic-go to v0.37.5 (#2497)
* Small changes for new quic-go API

* Update quic-go dependency

* Manually bump Go version in go-test

* Don't run examples in Go 1.21 yet

Revert this commit when we release a new go-libp2p version compatible
with Go 1.21

* update quic-go to v0.37.5

---------

Co-authored-by: Marco Munizaga <git@marcopolo.io>
2023-08-17 00:26:56 -07:00

40 lines
713 B
Go

//go:build !go1.21
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")
}