github.com/hyperledger/aries-framework-go@v0.3.2/pkg/internal/test/transportutil/utils.go (about) 1 /* 2 Copyright SecureKey Technologies Inc. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package transportutil 8 9 import ( 10 "errors" 11 "net" 12 "time" 13 ) 14 15 // GetRandomPort returns a available random local port. 16 func GetRandomPort(n int) int { 17 for ; n > 0; n-- { 18 port, err := getRandomPort() 19 if err != nil { 20 continue 21 } 22 23 return port 24 } 25 panic("cannot acquire the random port") 26 } 27 28 func getRandomPort() (int, error) { 29 const network = "tcp" 30 31 addr, err := net.ResolveTCPAddr(network, "localhost:0") 32 if err != nil { 33 return 0, err 34 } 35 36 listener, err := net.ListenTCP(network, addr) 37 if err != nil { 38 return 0, err 39 } 40 41 err = listener.Close() 42 if err != nil { 43 return 0, err 44 } 45 46 return listener.Addr().(*net.TCPAddr).Port, nil 47 } 48 49 // VerifyListener verifies if the host/port is available for listening. 50 func VerifyListener(host string, d time.Duration) error { 51 timeout := time.After(d) 52 53 for { 54 select { 55 case <-timeout: 56 return errors.New("timeout: server is not available") 57 default: 58 conn, err := net.Dial("tcp", host) 59 if err != nil { 60 continue 61 } 62 63 return conn.Close() 64 } 65 } 66 }