-
-
Save hsm2k3/efc2173e42c543461e52fed92f53ba12 to your computer and use it in GitHub Desktop.
get free port in golang
This file contains 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
// 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