Merge "lib/testutil/integration: modifyied API and first use of auto-generated stub support."
diff --git a/lib/testutil/util.go b/lib/testutil/util.go
index 6dc0b56..e95a253 100644
--- a/lib/testutil/util.go
+++ b/lib/testutil/util.go
@@ -5,6 +5,7 @@
"path/filepath"
"runtime"
"sync"
+ "syscall"
)
var (
@@ -77,3 +78,25 @@
copy(buffer, random[start:start+size])
return buffer
}
+
+// FindUnusedPort finds an unused port and returns it. Of course, no guarantees
+// are made that the port will actually be available by the time the caller
+// gets around to binding to it.
+func FindUnusedPort() (int, error) {
+ fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)
+ if err != nil {
+ return 0, err
+ }
+ defer syscall.Close(fd)
+
+ sa := &syscall.SockaddrInet4{}
+ err = syscall.Bind(fd, sa)
+ if err != nil {
+ return 0, err
+ }
+ name, err := syscall.Getsockname(fd)
+ if err != nil {
+ return 0, err
+ }
+ return name.(*syscall.SockaddrInet4).Port, nil
+}
diff --git a/tools/findunusedport/main.go b/tools/findunusedport/main.go
index de43476..18bb32d 100644
--- a/tools/findunusedport/main.go
+++ b/tools/findunusedport/main.go
@@ -4,28 +4,18 @@
import (
"fmt"
- "math/rand"
- "os"
- "syscall"
+ "v.io/core/veyron/lib/testutil"
"v.io/core/veyron2/vlog"
)
func main() {
- rand.Seed(int64(os.Getpid()))
- for i := 0; i < 1000; i++ {
- port := 1024 + rand.Int31n(64512)
- fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)
- if err != nil {
- continue
- }
- sa := &syscall.SockaddrInet4{Port: int(port)}
- if err := syscall.Bind(fd, sa); err != nil {
- continue
- }
- syscall.Close(fd)
+ port, err := testutil.FindUnusedPort()
+ if err != nil {
+ vlog.Fatalf("can't find unused port: %v\n", err)
+ } else if port == 0 {
+ vlog.Fatalf("can't find unused port")
+ } else {
fmt.Println(port)
- return
}
- vlog.Fatal("can't find unused port")
}