add util to find open ports

This commit is contained in:
Zack Scholl 2020-09-21 05:51:50 -07:00
parent dab52b4af7
commit 78e4d5e179
2 changed files with 23 additions and 0 deletions

View File

@ -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
}

View File

@ -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)
}