mirror of
https://github.com/v2fly/v2ray-core.git
synced 2024-12-21 01:27:03 -05:00
Refine pick port logic (#481)
This commit is contained in:
parent
ff09993c8b
commit
45aeaa8080
@ -1,16 +1,20 @@
|
||||
package tcp
|
||||
|
||||
import (
|
||||
"v2ray.com/core/common"
|
||||
"v2ray.com/core/common/net"
|
||||
)
|
||||
import "v2ray.com/core/common/net"
|
||||
|
||||
// PickPort returns an unused TCP port in the system. The port returned is highly likely to be unused, but not guaranteed.
|
||||
// PickPort returns an unused TCP port of the system.
|
||||
func PickPort() net.Port {
|
||||
listener, err := net.Listen("tcp4", "127.0.0.1:0")
|
||||
common.Must(err)
|
||||
listener := pickPort()
|
||||
defer listener.Close()
|
||||
|
||||
addr := listener.Addr().(*net.TCPAddr)
|
||||
return net.Port(addr.Port)
|
||||
}
|
||||
|
||||
func pickPort() net.Listener {
|
||||
listener, err := net.Listen("tcp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
listener = pickPort()
|
||||
}
|
||||
return listener
|
||||
}
|
||||
|
@ -1,19 +1,23 @@
|
||||
package udp
|
||||
|
||||
import (
|
||||
"v2ray.com/core/common"
|
||||
"v2ray.com/core/common/net"
|
||||
)
|
||||
import "v2ray.com/core/common/net"
|
||||
|
||||
// PickPort returns an unused UDP port in the system. The port returned is highly likely to be unused, but not guaranteed.
|
||||
// PickPort returns an unused UDP port of the system.
|
||||
func PickPort() net.Port {
|
||||
conn, err := net.ListenUDP("udp4", &net.UDPAddr{
|
||||
IP: net.LocalHostIP.IP(),
|
||||
Port: 0,
|
||||
})
|
||||
common.Must(err)
|
||||
conn := pickPort()
|
||||
defer conn.Close()
|
||||
|
||||
addr := conn.LocalAddr().(*net.UDPAddr)
|
||||
return net.Port(addr.Port)
|
||||
}
|
||||
|
||||
func pickPort() *net.UDPConn {
|
||||
conn, err := net.ListenUDP("udp4", &net.UDPAddr{
|
||||
IP: net.LocalHostIP.IP(),
|
||||
Port: 0,
|
||||
})
|
||||
if err != nil {
|
||||
conn = pickPort()
|
||||
}
|
||||
return conn
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user