1package connection 2 3import ( 4 "errors" 5 "fmt" 6 "net" 7 "strings" 8) 9 10// IsPortAvailable returns true if there's no listeners on a given port 11func IsPortAvailable(port int) bool { 12 conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%v", port)) 13 if err != nil { 14 if strings.Index(err.Error(), "connection refused") > 0 { 15 return true 16 } 17 return false 18 } 19 20 conn.Close() 21 return false 22} 23 24// FindAvailablePort returns the first available TCP port in the range 25func FindAvailablePort(start int, limit int) (int, error) { 26 for i := start; i <= (start + limit); i++ { 27 if IsPortAvailable(i) { 28 return i, nil 29 } 30 } 31 return -1, errors.New("No available port") 32} 33