github.com/iotexproject/iotex-core@v1.14.1-rc1/testutil/network.go (about)

     1  // Copyright (c) 2019 IoTeX Foundation
     2  // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
     3  // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
     4  // This source code is governed by Apache License 2.0 that can be found in the LICENSE file.
     5  
     6  package testutil
     7  
     8  import (
     9  	"math/rand"
    10  	"net"
    11  	"strconv"
    12  	"time"
    13  )
    14  
    15  func checkPortIsOpen(port int) bool {
    16  	timeout := time.Millisecond * 10
    17  	conn, err := net.DialTimeout("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)), timeout)
    18  	if err != nil {
    19  		return false
    20  	}
    21  	defer conn.Close()
    22  	return true
    23  }
    24  
    25  // RandomPort returns a random port number between 30000 and 50000
    26  func RandomPort() int {
    27  	r := rand.New(rand.NewSource(time.Now().UnixNano()))
    28  	var port int
    29  	for port = r.Intn(2000) + 30000; port < 50000; port++ {
    30  		if !checkPortIsOpen(port) {
    31  			break
    32  		}
    33  	}
    34  	return port
    35  }