• golang查找端口号占用的进程号


    golang官方包:

    https://studygolang.com/pkgdoc

    os

    支持获取当前进程pid并kill、但是仅仅限于获取当前进程pid

    FindProcess().Kill()
    os.Getpid()

    基础用法;但是却没有提供依据端口号获取对应的pid,所以还是执行shell指令对结果集进行过滤获取pid

    // 获取8299端口对应进程号并kill
    processInfo := exec.Command("/bin/sh", "-c",`lsof -i:8299 | awk '{print $2}' | awk  'NR==2{print}'`)
    if pid, err := processInfo.Output(); err != nil {
        fmt.Println(err.Error())
    }else{
        fmt.Println(string(pid))
        processExit := exec.Command("/bin/sh", "-c",`kill `+string(pid))
        if _, err := processExit.Output(); err != nil {
            fmt.Println(err.Error())
        }
    }

    and

    // 传入查询的端口号
    // 返回端口号对应的进程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
    }

    端口检测:

    func ScanPort(protocol string, hostname string, port int) bool {
     fmt.Printf("scanning port %d \n", port)
     p := strconv.Itoa(port)
     addr := net.JoinHostPort(hostname, p)
     conn, err := net.DialTimeout(protocol, addr, 3*time.Second)
     if err != nil {
     return false
     }
     defer conn.Close()
     return true
    }

    参考博客:

    https://www.jb51.net/article/208384.htm

    I can see a bigger world.
  • 相关阅读:
    elk 分布式数据同步
    mget 同时获取
    Jzoj1460 无题noname
    Jzoj1460 无题noname
    Jzoj1322硬币
    Jzoj1322硬币
    Jzoj1321 灯
    Jzoj1321 灯
    Jzoj1310 生日礼物
    Jzoj1310 生日礼物
  • 原文地址:https://www.cnblogs.com/xuweiqiang/p/15560119.html
Copyright © 2020-2023  润新知