1
0

port.go 456 B

12345678910111213141516171819
  1. package udp
  2. import (
  3. "github.com/xtls/xray-core/common"
  4. "github.com/xtls/xray-core/common/net"
  5. )
  6. // PickPort returns an unused UDP port in the system. The port returned is highly likely to be unused, but not guaranteed.
  7. func PickPort() net.Port {
  8. conn, err := net.ListenUDP("udp4", &net.UDPAddr{
  9. IP: net.LocalHostIP.IP(),
  10. Port: 0,
  11. })
  12. common.Must(err)
  13. defer conn.Close()
  14. addr := conn.LocalAddr().(*net.UDPAddr)
  15. return net.Port(addr.Port)
  16. }