mirror of
https://github.com/schollz/croc.git
synced 2025-10-11 21:30:16 +02:00
add util to find open ports
This commit is contained in:
parent
dab52b4af7
commit
78e4d5e179
2 changed files with 23 additions and 0 deletions
|
@ -16,6 +16,7 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/cespare/xxhash"
|
"github.com/cespare/xxhash"
|
||||||
"github.com/kalafut/imohash"
|
"github.com/kalafut/imohash"
|
||||||
|
@ -242,3 +243,20 @@ func RandomFileName() (fname string, err error) {
|
||||||
fname = f.Name()
|
fname = f.Name()
|
||||||
return
|
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
|
||||||
|
}
|
||||||
|
|
|
@ -186,3 +186,8 @@ func TestGetRandomName(t *testing.T) {
|
||||||
name := GetRandomName()
|
name := GetRandomName()
|
||||||
assert.NotEmpty(t, name)
|
assert.NotEmpty(t, name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestFindOpenPorts(t *testing.T) {
|
||||||
|
openPorts := FindOpenPorts("localhost", 9009, 4)
|
||||||
|
assert.Equal(t, []int{9009, 9010, 9011, 9012}, openPorts)
|
||||||
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue