Last active
December 11, 2023 01:07
-
-
Save HamzaRahmani/111bc5605ef1b5893c3abcbe5dc821ce to your computer and use it in GitHub Desktop.
Go - FreeTCPPort
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
// 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