From ec346409f7db840d3a760fdd36b5f3fdb5ccfadc Mon Sep 17 00:00:00 2001 From: ZacharyZcR <2903735704@qq.com> Date: Wed, 18 Dec 2024 22:19:40 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20=E4=BC=98=E5=8C=96ParsePort.go=E7=9A=84?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=EF=BC=8C=E6=B7=BB=E5=8A=A0=E6=B3=A8=E9=87=8A?= =?UTF-8?q?=EF=BC=8C=E8=A7=84=E8=8C=83=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Common/ParsePort.go | 41 ++++++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/Common/ParsePort.go b/Common/ParsePort.go index cec40e8..9363913 100644 --- a/Common/ParsePort.go +++ b/Common/ParsePort.go @@ -1,32 +1,46 @@ package Common import ( + "fmt" + "sort" "strconv" "strings" ) -func ParsePort(ports string) (scanPorts []int) { +// ParsePort 解析端口配置字符串为端口号列表 +func ParsePort(ports string) []int { if ports == "" { - return + return nil } + + var scanPorts []int slices := strings.Split(ports, ",") + + // 处理每个端口配置 for _, port := range slices { port = strings.TrimSpace(port) if port == "" { continue } + + // 处理预定义端口组 if PortGroup[port] != "" { - port = PortGroup[port] - scanPorts = append(scanPorts, ParsePort(port)...) + groupPorts := ParsePort(PortGroup[port]) + scanPorts = append(scanPorts, groupPorts...) + fmt.Printf("[*] 解析端口组 %s -> %v\n", port, groupPorts) continue } + + // 处理端口范围 upper := port if strings.Contains(port, "-") { ranges := strings.Split(port, "-") if len(ranges) < 2 { + fmt.Printf("[!] 无效的端口范围格式: %s\n", port) continue } + // 确保起始端口小于结束端口 startPort, _ := strconv.Atoi(ranges[0]) endPort, _ := strconv.Atoi(ranges[1]) if startPort < endPort { @@ -37,27 +51,40 @@ func ParsePort(ports string) (scanPorts []int) { upper = ranges[0] } } + + // 生成端口列表 start, _ := strconv.Atoi(port) end, _ := strconv.Atoi(upper) for i := start; i <= end; i++ { if i > 65535 || i < 1 { + fmt.Printf("[!] 忽略无效端口: %d\n", i) continue } scanPorts = append(scanPorts, i) } } + + // 去重并排序 scanPorts = removeDuplicate(scanPorts) + sort.Ints(scanPorts) + + fmt.Printf("[*] 共解析 %d 个有效端口\n", len(scanPorts)) return scanPorts } +// removeDuplicate 对整数切片进行去重 func removeDuplicate(old []int) []int { - result := []int{} - temp := map[int]struct{}{} + // 使用map存储不重复的元素 + temp := make(map[int]struct{}) + var result []int + + // 遍历并去重 for _, item := range old { - if _, ok := temp[item]; !ok { + if _, exists := temp[item]; !exists { temp[item] = struct{}{} result = append(result, item) } } + return result }