package system import ( "fmt" "net" "strconv" "time" ) // FreePort reports whether a TCP port can be bound on all interfaces. func FreePort(port int) bool { if port < 1 || port > 65535 { return false } ln, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", port)) if err != nil { return false } _ = ln.Close() // Give the kernel a moment to release the socket before the caller starts // a service that will bind it. time.Sleep(20 * time.Millisecond) return true } // AllocatePort finds a free port in [from,to] that is neither reserved in the // panel database nor bound by another process. func AllocatePort(from, to int, reserved map[int]string) (int, error) { if from < 1024 { from = 8000 } if to <= from || to > 65535 { to = from + 1000 } for p := from; p <= to; p++ { if _, used := reserved[p]; used { continue } if !FreePort(p) { continue } return p, nil } return 0, fmt.Errorf("端口区间 %d-%d 已无可分配端口", from, to) } // Listening reports whether something already listens on host:port. func Listening(host string, port int) bool { conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, strconv.Itoa(port)), 300*time.Millisecond) if err != nil { return false } _ = conn.Close() return true }