Here, we will learn how to get free port in go. We will use net package and ResolveTCPAddr method to get free port in go.
Program will interact with kernel for a free open port that is ready to use on localhost.
Example with code:
package main
import (
"fmt"
"net"
)
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() {
free_port, err := GetFreePort()
if free_port != 0 {
fmt.Println("Free port is: ", free_port)
} else {
fmt.Println("Free port is not available. Error is: ", err)
}
}
Output:
$ go run sample.go
Free port is: 62057
To learn more about golang, Please refer given below link:
https://www.techieindoor.com/go-lang-tutorial/
References:
https://golang.org/doc/
https://golang.org/pkg/