Created
March 21, 2020 16:45
-
-
Save ulrich/30673fe117fde8fbb5f74d4ef30fbb8d to your computer and use it in GitHub Desktop.
Return a free port available in a range of provided ports.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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