Menu Close

Go – How to get free port in go

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://techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, Miscellaneous, net

Leave a Reply

Your email address will not be published. Required fields are marked *