24 lines
440 B
Go
Raw Permalink Normal View History

2017-11-14 23:45:07 +01:00
package udp
import "github.com/v2fly/v2ray-core/v5/common/net"
2017-11-14 23:45:07 +01:00
2020-12-02 23:48:32 +08:00
// PickPort returns an unused UDP port of the system.
2017-11-14 23:45:07 +01:00
func PickPort() net.Port {
2020-12-02 23:48:32 +08:00
conn := pickPort()
2017-11-14 23:45:07 +01:00
defer conn.Close()
addr := conn.LocalAddr().(*net.UDPAddr)
return net.Port(addr.Port)
}
2020-12-02 23:48:32 +08:00
func pickPort() *net.UDPConn {
conn, err := net.ListenUDP("udp4", &net.UDPAddr{
IP: net.LocalHostIP.IP(),
Port: 0,
})
if err != nil {
conn = pickPort()
}
return conn
}