1
0

Use 127.0.0.0/8 only on linux

This commit is contained in:
dump_stack() 2018-09-20 23:47:36 +00:00
parent 667c42a8c6
commit 2acf22802e

View File

@ -12,6 +12,7 @@ import (
"net"
"os"
"os/exec"
"runtime"
"syscall"
"time"
@ -117,14 +118,29 @@ func getRandomAddrPort() (addr string) {
return fmt.Sprintf("%s:%d", ip, port)
}
func getRandomPort(ip string) (addr string) {
// ip:1024-65535
port := rand.Int()%(65535-1024) + 1024
return fmt.Sprintf("%s:%d", ip, port)
}
func getFreeAddrPort() (addrPort string) {
timeout := time.Now().Add(time.Second)
for {
addrPort = getRandomAddrPort()
if runtime.GOOS == "linux" {
addrPort = getRandomAddrPort()
} else {
addrPort = getRandomPort("127.0.0.1")
}
ln, err := net.Listen("tcp", addrPort)
if err == nil {
ln.Close()
return
}
if time.Now().After(timeout) {
panic("Can't found free address:port on localhost")
}
}
}