2015-05-19 01:13:17 +03:00
|
|
|
package connection
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2018-12-04 21:42:37 +03:00
|
|
|
// IsPortAvailable returns true if there's no listeners on a given port
|
|
|
|
func IsPortAvailable(port int) bool {
|
2015-05-19 01:13:17 +03:00
|
|
|
conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%v", port))
|
|
|
|
if err != nil {
|
|
|
|
if strings.Index(err.Error(), "connection refused") > 0 {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
conn.Close()
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2018-12-04 21:42:37 +03:00
|
|
|
// FindAvailablePort returns the first available TCP port in the range
|
|
|
|
func FindAvailablePort(start int, limit int) (int, error) {
|
2015-05-19 01:13:17 +03:00
|
|
|
for i := start; i <= (start + limit); i++ {
|
2018-12-04 21:42:37 +03:00
|
|
|
if IsPortAvailable(i) {
|
2015-05-19 01:13:17 +03:00
|
|
|
return i, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return -1, errors.New("No available port")
|
|
|
|
}
|