Last active
February 7, 2021 16:03
-
-
Save danil/54780659696537612d935ccad82a83bc to your computer and use it in GitHub Desktop.
Free random TCP port listener
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
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