miaopanel
1package system
2
3import (
4 "fmt"
5 "net"
6 "strconv"
7 "time"
8)
9
10// FreePort reports whether a TCP port can be bound on all interfaces.
11func FreePort(port int) bool {
12 if port < 1 || port > 65535 {
13 return false
14 }
15 ln, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", port))
16 if err != nil {
17 return false
18 }
19 _ = ln.Close()
20 // Give the kernel a moment to release the socket before the caller starts
21 // a service that will bind it.
22 time.Sleep(20 * time.Millisecond)
23 return true
24}
25
26// AllocatePort finds a free port in [from,to] that is neither reserved in the
27// panel database nor bound by another process.
28func AllocatePort(from, to int, reserved map[int]string) (int, error) {
29 if from < 1024 {
30 from = 8000
31 }
32 if to <= from || to > 65535 {
33 to = from + 1000
34 }
35 for p := from; p <= to; p++ {
36 if _, used := reserved[p]; used {
37 continue
38 }
39 if !FreePort(p) {
40 continue
41 }
42 return p, nil
43 }
44 return 0, fmt.Errorf("端口区间 %d-%d 已无可分配端口", from, to)
45}
46
47// Listening reports whether something already listens on host:port.
48func Listening(host string, port int) bool {
49 conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, strconv.Itoa(port)), 300*time.Millisecond)
50 if err != nil {
51 return false
52 }
53 _ = conn.Close()
54 return true
55}