Skip to content

Instantly share code, notes, and snippets.

@HamzaRahmani
Last active December 11, 2023 01:07
Show Gist options
  • Save HamzaRahmani/111bc5605ef1b5893c3abcbe5dc821ce to your computer and use it in GitHub Desktop.
Save HamzaRahmani/111bc5605ef1b5893c3abcbe5dc821ce to your computer and use it in GitHub Desktop.
Go - FreeTCPPort
// GetFreeTCPPort asks the kernel for a free open port that is ready to use.
func GetFreeTCPPort() (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