mirror of
https://github.com/MichaelMure/git-bug.git
synced 2024-12-15 02:01:43 +03:00
31 lines
580 B
Go
31 lines
580 B
Go
|
package freeport
|
||
|
|
||
|
import (
|
||
|
"net"
|
||
|
)
|
||
|
|
||
|
// GetFreePort asks the kernel for a free open port that is ready to use.
|
||
|
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
|
||
|
}
|
||
|
|
||
|
// GetPort is deprecated, use GetFreePort instead
|
||
|
// Ask the kernel for a free open port that is ready to use
|
||
|
func GetPort() int {
|
||
|
port, err := GetFreePort()
|
||
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
return port
|
||
|
}
|