Last active
January 18, 2023 08:00
-
-
Save kemokemo/2d94e079dba5be3d73b482545296d6b3 to your computer and use it in GitHub Desktop.
Get free port sample. Respect to https://github.com/phayes/freeport.
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" | |
) | |
// GetFreePort returns the available port of the local environment. | |
func GetFreePort() (int, error) { | |
addr, err := net.ResolveTCPAddr("tcp", "localhost:0") | |
if err != nil { | |
return 0, err | |
} | |
l, err := net.ListenTCP("tcp", addr) | |
if err != nil { | |
return 0, err | |
} | |
defer l.Close() | |
return l.Addr().(*net.TCPAddr).Port, nil | |
} | |
func main() { | |
freePort, err := GetFreePort() | |
if freePort != 0 { | |
fmt.Printf("%v", freePort) | |
} else { | |
fmt.Println("Free port is not available. Error is: ", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment