• Golang检测Linux服务器端口占用


    • 代码实现
    func CheckPort(port int) error {
        checkStatement := fmt.Sprintf(`netstat -anp | grep -q %d ; echo $?`, port)
        output, err := exec.Command("sh", "-c", checkStatement).CombinedOutput()
        if err != nil {
            return err
        }
        // log.Println(output, string(output)) ==> [48 10] 0 或 [49 10] 1
        result, err := strconv.Atoi(strings.TrimSuffix(string(output), "
    "))
        if err != nil {
            return err
        }
        if result == 0 {
            return fmt.Errorf("端口%d已被占用", port)
        }
    
        return nil
    }
    

    - **纠错思路**
    • 第8行原代码为:result, err := strconv.Atoi(string(output)),
      报错为: strconv.Atoi: parsing "0 ": invalid syntax
    • 经排查,CombinedOutput()函数的执行结果0 (1 )包含换行符 ,
      利用strings.TrimSuffix()函数删除换行符


    • 延伸知识
      • strings.TrimSuffix()strings.TrimRight()的区别
    func main() {
    	str1 := "abcdabceeebdc"
    	str2 := "abcd"
    	str3 := "abced"
    	str4 := "ebdc"
        // `TrimRight(s, cutset string) string`指从`s`右端开始,删除所有`cutset`中出现的字符
        // 若从右到左的过程中遇到其他字符,则停止删除。  
    	fmt.Println(strings.TrimRight(str1, str2))    
    	fmt.Println("空行:", strings.TrimRight(str1, str3))   
    
        // `TrimSuffix(s, suffix string)`删除后缀`suffix` ,若不匹配,返回s
    	fmt.Println(strings.TrimSuffix(str1, str4))    
    	fmt.Println(strings.TrimSuffix(str1, str2))    
    }
    
    // 输出结果:
    // abcdabceee
    // 空行:
    // abcdabcee
    // abcdabceeebdc
    

    2019-09-24改

    func CheckPort(port int) error {
        checkStatement := fmt.Sprintf("netstat -anp | grep -q %d ", port)
        output, err := exec.Command("sh", "-c", checkStatement).CombinedOutput()
        if err != nil {
            return nil   // err != nil 说明端口没被占用
        }
    
        if len(output) > 0 {
            return fmt.Errorf("端口%d已被占用", port)
        }
    
        return nil
    }
    

    注:以上方法的缺陷是目标操作系统上有可能没有netstat命令

    2019-09-29改

    
    func CheckPort(port string) error {
    	var err error
    	
    	tcpAddress, err := net.ResolveTCPAddr("tcp4", ":" + port)
    	if err != nil {
    		return err
    	}
    	
    	for i := 0; i < 3; i++ {
    		listener, err := net.ListenTCP("tcp", tcpAddress)
    		if err != nil {
    			time.Sleep(time.Duration(100) * time.Millisecond)
    			if i == 3 {
    				return err
    			}
    			continue
    		} else {
    			listener.Close()
    			break
    		}
    	}
    
    	return nil
    }
    
  • 相关阅读:
    2019 ICPC Nanchang Summon
    2018 Multi-University Training Contest 10 B. Beads
    2020 ICPC Shanghai C
    2020 ICPC Shanghai B
    2020 ICPC Shanghai I
    2018 ICPC Shenyang G
    ACM-ICPC 2017 Asia Qingdao Suffix
    2018 Multi-University Training Contest 10 Calculate
    ACM-ICPC 2017 Asia Qingdao Our Journey of Xian Ends
    Java8-无限流补全日期,折线图补零
  • 原文地址:https://www.cnblogs.com/GaiHeiluKamei/p/11453623.html
Copyright © 2020-2023  润新知