Skip to content

Instantly share code, notes, and snippets.

@ulrich
Created March 21, 2020 16:45
Show Gist options
  • Save ulrich/30673fe117fde8fbb5f74d4ef30fbb8d to your computer and use it in GitHub Desktop.
Save ulrich/30673fe117fde8fbb5f74d4ef30fbb8d to your computer and use it in GitHub Desktop.
Return a free port available in a range of provided ports.
package main
import (
"errors"
"fmt"
"net"
"strconv"
)
const (
start = 8084
end = start + 10
)
func main() {
availablePort, err := getFreePort()
if err != nil {
fmt.Printf("error: %v", err)
return
}
fmt.Printf("using port: %v", availablePort)
}
func getFreePort() (int, error) {
for port := start; port < end; port++ {
listener, err := net.Listen("tcp", ":"+strconv.Itoa(port))
if err == nil {
listener.Close()
return port, nil
}
}
return 0, errors.New("no port available")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment