diff --git a/src/utils/utils.go b/src/utils/utils.go index d148e10a..7fc074e0 100644 --- a/src/utils/utils.go +++ b/src/utils/utils.go @@ -16,6 +16,7 @@ import ( "net/http" "os" "strings" + "time" "github.com/cespare/xxhash" "github.com/kalafut/imohash" @@ -242,3 +243,20 @@ func RandomFileName() (fname string, err error) { fname = f.Name() return } + +func FindOpenPorts(host string, portNumStart, numPorts int) (openPorts []int) { + openPorts = []int{} + for port := portNumStart; port-portNumStart < 200; port++ { + timeout := 100 * time.Millisecond + conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, fmt.Sprint(port)), timeout) + if conn != nil { + conn.Close() + } else if err != nil { + openPorts = append(openPorts, port) + } + if len(openPorts) >= numPorts { + return + } + } + return +} diff --git a/src/utils/utils_test.go b/src/utils/utils_test.go index 496d59fc..cd7bd8cc 100644 --- a/src/utils/utils_test.go +++ b/src/utils/utils_test.go @@ -186,3 +186,8 @@ func TestGetRandomName(t *testing.T) { name := GetRandomName() assert.NotEmpty(t, name) } + +func TestFindOpenPorts(t *testing.T) { + openPorts := FindOpenPorts("localhost", 9009, 4) + assert.Equal(t, []int{9009, 9010, 9011, 9012}, openPorts) +}