github.com/v2fly/v2ray-core/v4@v4.45.2/testing/servers/tcp/port.go (about)

     1  package tcp
     2  
     3  import "github.com/v2fly/v2ray-core/v4/common/net"
     4  
     5  // PickPort returns an unused TCP port of the system.
     6  func PickPort() net.Port {
     7  	listener := pickPort()
     8  	defer listener.Close()
     9  
    10  	addr := listener.Addr().(*net.TCPAddr)
    11  	return net.Port(addr.Port)
    12  }
    13  
    14  func pickPort() net.Listener {
    15  	listener, err := net.Listen("tcp4", "127.0.0.1:0")
    16  	if err != nil {
    17  		listener = pickPort()
    18  	}
    19  	return listener
    20  }