Skip to content

Instantly share code, notes, and snippets.

@danil
Last active February 7, 2021 16:03
Show Gist options
  • Save danil/54780659696537612d935ccad82a83bc to your computer and use it in GitHub Desktop.
Save danil/54780659696537612d935ccad82a83bc to your computer and use it in GitHub Desktop.
Free random TCP port listener
package main
import (
"fmt"
"net"
)
func freeportln(s string) *net.TCPListener {
addr, err := net.ResolveTCPAddr("tcp", s)
if err != nil {
return nil
}
ln, err := net.ListenTCP("tcp", addr)
if err != nil {
return nil
}
return ln
}
func main() {
for i, ln := 0, freeportln(":0"); i < 3; i++ {
if ln == nil {
continue
}
defer ln.Close()
fmt.Println("random port", ln.Addr().(*net.TCPAddr).Port)
return
}
panic("attempts exceeded")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment