fix: Optimize container port detection mechanism

This commit is contained in:
ssongliu 2025-09-01 11:04:42 +08:00
parent 663196c3d9
commit 37efaa4fb1
2 changed files with 20 additions and 2 deletions

View file

@ -1429,7 +1429,7 @@ func checkPortStats(ports []dto.PortHelper) (nat.PortMap, error) {
portMap[nat.Port(fmt.Sprintf("%d/%s", containerStart+i, port.Protocol))] = []nat.PortBinding{bindItem}
}
for i := hostStart; i <= hostEnd; i++ {
if common.ScanPort(i) {
if common.ScanPortWithIP(port.HostIP, i) {
return portMap, buserr.WithDetail("ErrPortInUsed", i, nil)
}
}
@ -1440,7 +1440,7 @@ func checkPortStats(ports []dto.PortHelper) (nat.PortMap, error) {
} else {
portItem, _ = strconv.Atoi(port.HostPort)
}
if common.ScanPort(portItem) {
if common.ScanPortWithIP(port.HostIP, portItem) {
return portMap, buserr.WithDetail("ErrPortInUsed", portItem, nil)
}
bindItem := nat.PortBinding{HostPort: strconv.Itoa(portItem), HostIP: port.HostIP}

View file

@ -212,6 +212,24 @@ func ScanPortWithProto(port int, proto string) bool {
return ScanPort(port)
}
func ScanPortWithIP(ip string, port int) bool {
if len(ip) == 0 {
return ScanPort(port)
}
address := net.JoinHostPort(ip, fmt.Sprintf("%d", port))
timeout := time.Second * 2
conn, err := net.DialTimeout("tcp", address, timeout)
if err != nil {
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
return true
}
return false
}
defer conn.Close()
return true
}
func IsNum(s string) bool {
_, err := strconv.ParseFloat(s, 64)
return err == nil