Golang Free Port

Golang Free Port

Overview

随机选择一个本地没有被占用的端口号, 代码如下,

func freePort() int {
    addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
    if err != nil {
        panic(err)
    }

    l, err := net.ListenTCP("tcp", addr)
    if err != nil {
        panic(err)
    }
    defer l.Close()
 
    return l.Addr().(*net.TCPAddr).Port
}

原理

The port 0 trick

Tags:golang   Tags:network
Written on February 14, 2019