windows

// 传入查询的端口号
// 返回端口号对应的进程PID,若没有找到相关进程,返回-1

func portInUse(portNumber int) int {
    res := -1
    var outBytes bytes.Buffer
    cmdStr := fmt.Sprintf("netstat -ano -p tcp | findstr %d", portNumber)
    cmd := exec.Command("cmd", "/c", cmdStr)
    cmd.Stdout = &outBytes
    cmd.Run()
    resStr := outBytes.String()
    r := regexp.MustCompile(`\s\d+\s`).FindAllString(resStr, -1)
    if len(r) > 0 {
        pid, err := strconv.Atoi(strings.TrimSpace(r[0]))
        if err != nil {
            res = -1
        } else {
            res = pid
        }
    }
    return res
}

linux

func PortInUse(port int) bool {

    checkStatement := fmt.Sprintf("lsof -i:%d ", port)
    output, _ := exec.Command("sh", "-c", checkStatement).CombinedOutput()
    if len(output) > 0 {
        return true
    }
    return false
}
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
}

相关资料:https://www.cnblogs.com/GaiHeiluKamei/archive/2019/09/03/11453623.html

发表评论

邮箱地址不会被公开。 必填项已用*标注