Skip to content

Instantly share code, notes, and snippets.

@hsm2k3
Forked from sevkin/getfreeport.go
Created November 2, 2022 04:31
Show Gist options
  • Save hsm2k3/efc2173e42c543461e52fed92f53ba12 to your computer and use it in GitHub Desktop.
Save hsm2k3/efc2173e42c543461e52fed92f53ba12 to your computer and use it in GitHub Desktop.
get free port in golang
// GetFreePort asks the kernel for a free open port that is ready to use.
func GetFreePort() (port int, err error) {
var a *net.TCPAddr
if a, err = net.ResolveTCPAddr("tcp", "localhost:0"); err == nil {
var l *net.TCPListener
if l, err = net.ListenTCP("tcp", a); err == nil {
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment