pgweb/pkg/connection/port.go

33 lines
660 B
Go
Raw Normal View History

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 {
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) {
for i := start; i <= (start + limit); i++ {
2018-12-04 21:42:37 +03:00
if IsPortAvailable(i) {
return i, nil
}
}
return -1, errors.New("No available port")
}